`

Python Interview Questions And Answers Set - 8

阅读更多
How to use Sessions for Web python ?
Sessions are the server side version of cookies. While a cookie persists data (or state) at the client, sessions do it at the server. Sessions have the advantage that the data do not travel the network thus making it both safer and faster although this not entirely true as shown in the next paragraph

The session state is kept in a file or in a database at the server side. Each session is identified by an id or session id (SID). To make it possible to the client to identify himself to the server the SID must be created by the server and sent to the client and then sent back to the server whenever the client makes a request. There is still data going through the net, the SID.

The server can send the SID to the client in a link's query string or in a hidden form field or as a Set-Cookie header. The SID can be sent back from the client to the server as a query string parameter or in the body of the HTTP message if the post method is used or in a Cookie HTTP header.

If a cookie is not used to store the SID then the session will only last until the browser is closed, or the user goes to another site breaking the POST or query string transmission, or in other words, the session will last only until the user leaves the site.

* Cookie Based SID:

A cookie based session has the advantage that it lasts until the cookie expires and, as only the SID travels the net, it is faster and safer. The disadvantage is that the client must have cookies enabled.

The only particularity with the cookie used to set a session is its value:

# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()

The hash of the server time makes an unique SID for each session.

#!/usr/bin/env python

import sha, time, Cookie, os

cookie = Cookie.SimpleCookie()
string_cookie = os.environ.get('HTTP_COOKIE')

# If new session
if not string_cookie:
# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()
# Set the sid in the cookie
cookie['sid'] = sid
# Will expire in a year
cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60
# If already existent session
else:
cookie.load(string_cookie)
sid = cookie['sid'].value

print cookie
print 'Content-Type: text/html\n'
print '<html><body>'

if string_cookie:
print '<p>Already existent session</p>'
else:
print '<p>New session</p>'

print '<p>SID =', sid, '</p>'
print '</body></html>'

In every page the existence of the cookie must be tested. If it does not exist then redirect to a login page or just create it if a login or a previous state is not required.

* Query String SID;

Query string based session:

#!/usr/bin/env python

import sha, time, cgi, os

sid = cgi.FieldStorage().getfirst('sid')

if sid: # If session exists
message = 'Already existent session'
else: # New session
# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()
message = 'New session'

qs = 'sid=' + sid
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
<p>SID = %s</p>
<p><a href="./set_sid_qs.py?sid=%s">reload</a></p>
</body></html>
""" % (message, sid, sid)

To mantain a session you will have to append the query string to all the links in the page.

Save this file as set_sid_qs.py and run it two or more times. Try to close the browser and call the page again. The session is gone. The same happens if the page address is typed in the address bar.

* Hidden Field SID;

The hidden form field SID is almost the same as the query string based one, sharing the same problems.

#!/usr/bin/env python

import sha, time, cgi, os

sid = cgi.FieldStorage().getfirst('sid')

if sid: # If session exists
message = 'Already existent session'
else: # New session
# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()
message = 'New session'

qs = 'sid=' + sid

print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
<p>SID = %s</p>
<form method="post">
<input type="hidden" name=sid value="%s">
<input type="submit" value="Submit">
</form>
</body><html>
""" % (message, sid, sid)


* The shelve module;

Having a SID is not enough. It is necessary to save the session state in a file or in a database. To save it into a file the shelve module is used. The shelve module opens a file and returns a dictionary like object which is readable and writable as a dictionary.

# The shelve module will persist the session data
# and expose it as a dictionary
session = shelve.open('/tmp/.session/sess_' + sid, writeback=True)


The SID is part of file name making it a unique file. The apache user must have read and write permission on the file's directory. 660 would be ok.

The values of the dictionary can be any Python object. The keys must be immutable objects.

# Save the current time in the session
session['lastvisit'] = repr(time.time())

# Retrieve last visit time from the session
lastvisit = session.get('lastvisit')

The dictionary like object must be closed as any other file should be:

session.close()

* Cookie and Shelve;

A sample of how to make cookies and shelve work together keeping session state at the server side:

#!/usr/bin/env python
import sha, time, Cookie, os, shelve

cookie = Cookie.SimpleCookie()
string_cookie = os.environ.get('HTTP_COOKIE')

if not string_cookie:
sid = sha.new(repr(time.time())).hexdigest()
cookie['sid'] = sid
message = 'New session'
else:
cookie.load(string_cookie)
sid = cookie['sid'].value
cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60

# The shelve module will persist the session data
# and expose it as a dictionary
session = shelve.open('/tmp/.session/sess_' + sid, writeback=True)

# Retrieve last visit time from the session
lastvisit = session.get('lastvisit')
if lastvisit:
message = 'Welcome back. Your last visit was at ' + \
time.asctime(time.gmtime(float(lastvisit)))
# Save the current time in the session
session['lastvisit'] = repr(time.time())

print """\
%s
Content-Type: text/html\n
<html><body>
<p>%s</p>
<p>SID = %s</p>
</body></html>
""" % (cookie, message, sid)

session.close()

It first checks if there is a cookie already set. If not it creates a SID and attributes it to the cookie value. An expiration time of one year is established.

The lastvisit data is what is maintained in the session.

How to use Sessions for Web python ?
Sessions are the server side version of cookies. While a cookie persists data (or state) at the client, sessions do it at the server. Sessions have the advantage that the data do not travel the network thus making it both safer and faster although this not entirely true as shown in the next paragraph

The session state is kept in a file or in a database at the server side. Each session is identified by an id or session id (SID). To make it possible to the client to identify himself to the server the SID must be created by the server and sent to the client and then sent back to the server whenever the client makes a request. There is still data going through the net, the SID.

The server can send the SID to the client in a link's query string or in a hidden form field or as a Set-Cookie header. The SID can be sent back from the client to the server as a query string parameter or in the body of the HTTP message if the post method is used or in a Cookie HTTP header.

If a cookie is not used to store the SID then the session will only last until the browser is closed, or the user goes to another site breaking the POST or query string transmission, or in other words, the session will last only until the user leaves the site.

* Cookie Based SID:

A cookie based session has the advantage that it lasts until the cookie expires and, as only the SID travels the net, it is faster and safer. The disadvantage is that the client must have cookies enabled.

The only particularity with the cookie used to set a session is its value:

# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()

The hash of the server time makes an unique SID for each session.

#!/usr/bin/env python

import sha, time, Cookie, os

cookie = Cookie.SimpleCookie()
string_cookie = os.environ.get('HTTP_COOKIE')

# If new session
if not string_cookie:
# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()
# Set the sid in the cookie
cookie['sid'] = sid
# Will expire in a year
cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60
# If already existent session
else:
cookie.load(string_cookie)
sid = cookie['sid'].value

print cookie
print 'Content-Type: text/html\n'
print '<html><body>'

if string_cookie:
print '<p>Already existent session</p>'
else:
print '<p>New session</p>'

print '<p>SID =', sid, '</p>'
print '</body></html>'

In every page the existence of the cookie must be tested. If it does not exist then redirect to a login page or just create it if a login or a previous state is not required.

* Query String SID;

Query string based session:

#!/usr/bin/env python

import sha, time, cgi, os

sid = cgi.FieldStorage().getfirst('sid')

if sid: # If session exists
message = 'Already existent session'
else: # New session
# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()
message = 'New session'

qs = 'sid=' + sid
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
<p>SID = %s</p>
<p><a href="./set_sid_qs.py?sid=%s">reload</a></p>
</body></html>
""" % (message, sid, sid)

To mantain a session you will have to append the query string to all the links in the page.

Save this file as set_sid_qs.py and run it two or more times. Try to close the browser and call the page again. The session is gone. The same happens if the page address is typed in the address bar.

* Hidden Field SID;

The hidden form field SID is almost the same as the query string based one, sharing the same problems.

#!/usr/bin/env python

import sha, time, cgi, os

sid = cgi.FieldStorage().getfirst('sid')

if sid: # If session exists
message = 'Already existent session'
else: # New session
# The sid will be a hash of the server time
sid = sha.new(repr(time.time())).hexdigest()
message = 'New session'

qs = 'sid=' + sid

print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
<p>SID = %s</p>
<form method="post">
<input type="hidden" name=sid value="%s">
<input type="submit" value="Submit">
</form>
</body><html>
""" % (message, sid, sid)


* The shelve module;

Having a SID is not enough. It is necessary to save the session state in a file or in a database. To save it into a file the shelve module is used. The shelve module opens a file and returns a dictionary like object which is readable and writable as a dictionary.

# The shelve module will persist the session data
# and expose it as a dictionary
session = shelve.open('/tmp/.session/sess_' + sid, writeback=True)


The SID is part of file name making it a unique file. The apache user must have read and write permission on the file's directory. 660 would be ok.

The values of the dictionary can be any Python object. The keys must be immutable objects.

# Save the current time in the session
session['lastvisit'] = repr(time.time())

# Retrieve last visit time from the session
lastvisit = session.get('lastvisit')

The dictionary like object must be closed as any other file should be:

session.close()

* Cookie and Shelve;

A sample of how to make cookies and shelve work together keeping session state at the server side:

#!/usr/bin/env python
import sha, time, Cookie, os, shelve

cookie = Cookie.SimpleCookie()
string_cookie = os.environ.get('HTTP_COOKIE')

if not string_cookie:
sid = sha.new(repr(time.time())).hexdigest()
cookie['sid'] = sid
message = 'New session'
else:
cookie.load(string_cookie)
sid = cookie['sid'].value
cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60

# The shelve module will persist the session data
# and expose it as a dictionary
session = shelve.open('/tmp/.session/sess_' + sid, writeback=True)

# Retrieve last visit time from the session
lastvisit = session.get('lastvisit')
if lastvisit:
message = 'Welcome back. Your last visit was at ' + \
time.asctime(time.gmtime(float(lastvisit)))
# Save the current time in the session
session['lastvisit'] = repr(time.time())

print """\
%s
Content-Type: text/html\n
<html><body>
<p>%s</p>
<p>SID = %s</p>
</body></html>
""" % (cookie, message, sid)

session.close()

It first checks if there is a cookie already set. If not it creates a SID and attributes it to the cookie value. An expiration time of one year is established.

The lastvisit data is what is maintained in the session.

分享到:
评论

相关推荐

    [net毕业设计]ASP.NET基于BS结构的实验室预约模型系统(源代码+论文).zip

    【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。

    中医诊所系统,WPF.zip

    中医诊所系统,WPF.zip

    [net毕业设计]ASP.NET淘宝店主交易管理系统的设计与实现(源代码+论文).zip

    【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。

    1-全国各省、297个地级市公路里程面板数据1999-2021年-社科数据.zip

    全国各省、297个地级市公路里程面板数据1999-2021年涵盖了中国各地区公路建设的详细情况,是衡量地区基础设施水平的重要指标。这些数据不仅包括了全国31个省份的公路里程,还深入到了297个地级市的层面,提供了从1999年至2021年的连续年份数据。这些数据来源于各省统计年鉴、经济社会发展统计数据库、地级市统计年鉴以及地级市发展统计公报,确保了数据的准确性和权威性。通过这些数据,可以观察到中国公路交通建设的发展不平衡性,沿海地区和长江中下游地区公路交通密度较高,而西部地区相对较低。这些面板数据为研究中国城市化进程、区域经济发展以及交通基础设施建设提供了宝贵的信息资源。

    技术处工作事项延期完成申请单.docx

    技术处工作事项延期完成申请单.docx

    数据库详细设计说明书中文最新版本

    本文为图书馆管理课程设计SQL Server功能规范说明书。本说明书将: 描述数据库设计的目的; 说明数据库设计中的主要组成部分; 说明数据库设计中各功能的实现。 本文档主要内容包括对数据库设计结构的总体描述,对数据库中各种对象的描述(包括对象的名称、对象的属性、对象和其他对象直接的关系);在数据库主要对象之外,本文还将描述数据库安全性设置、数据库属性设置和数据库备份策略,为数据库管理员维护数据库安全稳定地运行提供参考;有需要的朋友可以下载看看

    WebSocketError(解决方案).md

    项目中常见的问题,记录一下解决方案

    octopart(样本).csv

    octopart数据格式样例

    [net毕业设计]ASP.NET通用作业批改系统设计(源代码+论文).zip

    【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。

    Oracle11gRAC安装与配置forLinux中文最新版本

    本文档主要讲述的是Oracle 11g RAC安装与配置for Linux;希望对大家的学习会有帮助 文档结构 第一部分:Oracle Grid Infrastructure安装 第二部分:Oracle Clusterware与Oracle Real Application Clusters安装前准备规程 第三部分:安装Oracle Clusterware与Oracle Real Application Clusters 第四部分:Oracle Real Application Clusters环境配置 第五部分:Oracle Clusterware与Oracle Real Application Clusters参考资料

    python教程.txt

    python教程.txt

    脸部痤疮检测数据集VOC+YOLO格式3763张7类别.zip

    文件太大放服务器下请务必到资源详情查看后然后下载 样本图:blog.csdn.net/2403_88102872/article/details/143979016 重要说明:数据集为小目标检测,训练map精度偏低属于正常现象,只要能检测出来即可。如果map低于0.5请勿奇怪,因为小目标检测是业界公认难检测的研究方向之一。 数据集格式:Pascal VOC格式+YOLO格式(不包含分割路径的txt文件,仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数):3763 标注数量(xml文件个数):3763 标注数量(txt文件个数):3763 标注类别数:7 标注类别名称:["blackheads","cyst","fore","nodule","papule","pustule","whiteheads"]

    ASP+ACCESS基于WEB社区论坛设计与实现(源代码+论文)(源代码+论文+说明文档).zip

    【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。

    1-全国各地级市固定资产投资统计数据(附省、区县、行业)1996-2020年-社科数据.zip

    全国各地级市固定资产投资统计数据集覆盖了1996至2020年的时间跨度,提供了详尽的年度固定资产投资金额,单位为百万人民币。这些数据不仅包括了地级市级别的投资情况,还涵盖了省、区县以及行业等多个维度,为研究区域经济增长、投资结构和发展趋势提供了宝贵的数据支持。固定资产投资作为衡量一个地区经济发展活力和潜力的重要指标,反映了社会固定资产在生产、投资额的规模和速度。通过这些数据,研究人员可以深入分析不同地区、不同行业的投资特点,以及随时间变化的趋势,进而为政策制定和经济预测提供科学依据。

    training_plan_db.sql

    training_plan_db.sql

    [net毕业设计]ASP.NET多语种网络硬盘系统的设计(源代码+论文).zip

    【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。

    5.html

    5

    1-全国各省地区城乡收入差距、泰尔指数、城镇农村居民可支配收入统计数据1990-2021年-社科数据.zip

    全国各省地区城乡收入差距、泰尔指数、城镇农村居民可支配收入统计数据集提供了1990至2021年间的详细数据,覆盖全国31个省份。该数据集不仅包括城镇居民和农村居民的人均可支配收入,还涵盖了乡村人口、全体居民人均可支配收入、城镇人口以及年末常住人口等关键指标。泰尔指数作为衡量收入不平等的重要工具,通过计算城镇收入与农村收入之比,为研究者提供了一个量化城乡收入差距的科学方法。这些数据不仅有助于分析中国城乡之间的经济差异,还能为政策制定者提供决策支持,以缩小城乡差距、促进区域均衡发展。数据集的丰富性使其成为社会科学领域研究城乡发展、收入分配不平等等问题的宝贵资源。

    FileName.zip

    FileName.zip

    java面向对象 - 类与对象代码.zip

    java面向对象 - 类与对象java面向对象 - 类与对象代码.zip

Global site tag (gtag.js) - Google Analytics