`

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.

分享到:
评论

相关推荐

    sap-basis-certification-questions-sap-basis-interview-questions-answers-and-explanations

    SAP Basis Interview Questions 在进行 SAP Basis 的面试准备时,面试官通常会关注应聘者对 SAP Basis 的基础知识和实践经验的理解。例如: - **问题示例**:“请简要介绍 SAP Basis 并解释它的主要功能。” - **...

    Top 20 Core Java Interview Questions and Answers

    从国外网站上下载的Java面试题。可以看看国外公司的Java面试常用题,以及如何用英文回答。

    115-Java-Interview-Questions-and-Answers, 115 Java访谈问题和答案- 终极列表.zip

    115-Java-Interview-Questions-and-Answers, 115 Java访谈问题和答案- 终极列表 #115-Java-Interview-Questions-and-Answers我们将讨论关于Java面试中可以使用的各种问题,以便雇主在Java和面向对象编程方面测试你的...

    C++ interview questions and answers

    根据提供的文件信息,本文将对其中涉及的C++面试题目进行详细解析,并提供相应的答案,旨在帮助准备参加C++职位面试的求职者更好地理解和掌握相关的技术要点。 ### 1. C++基础知识 #### 1.1 什么是C++?...

    Java-Interview-Questions-and-Answers

    ### Java Interview Questions and Answers #### 1. 什么是 Java?解释其含义与定义。 Java 是当今最流行的编程语言之一,在 Web 应用程序、移动应用、软件开发、游戏系统以及服务器端技术等领域扮演着重要角色。...

    CISA Interview Questions and Answers学习文档手册.pdf

    CISA Interview Questions and Answers学习文档手册.pdf

    15 Toughest Interview Questions and Answers

    根据提供的文件信息,我们可以从中提炼出三个重要的面试问题及其回答策略。这不仅是对求职者面试技巧的考验,也是展示个人专业素养与职业态度的关键时刻。接下来,我们将详细解析这三个问题及如何给出恰当的回答。...

    interview questions 12 with answers.pdf

    ### IT面试问题与答案解析 #### 1. 如何描述自己? **优秀示例回答:** 我的背景至今一直围绕着成为一名最优秀的财务顾问而努力。让我具体介绍一下我是如何准备自己的。我是一名在______大学主修金融和会计的本科...

    SAP ABAP Certification Review SAP ABAP Interview Questions, Answers, And Explanations.pdf

    SAP ABAP Certification Review SAP ABAP Interview Questions, Answers, And Explanations.pdf

    SAP+SD+Interview+Questions+Answers+and+Explanations

    8. **条件类型与定价程序(Condition Type and Pricing Procedure)** 9. **使用事务码创建销售人员(Using TransMass to Create Sales Rep)** 10. **序列号(Serial Numbers)** 11. **变体定价(Variant Pricing)** 12. ...

    Java-Spring-Boot-Interview-Questions-and-Answers:最受欢迎的Java面试问答

    本资料“Java-Spring-Boot-Interview-Questions-and-Answers”集合了最受欢迎的Java及Spring Boot面试问题,帮助求职者准备相关面试。 一、Java基础 1. 讲解Java内存模型(JVM)的结构,包括堆内存、栈内存、方法区...

    ABAP WebDynpro Interview questions and answers

    - **设置可编辑模式**: 使用 `set_read_only` 方法将 ALV 设置为可编辑模式,该方法在接口 `IF_SALV_WD_TABLE_SETTINGS` 实现类 `CL_SALV_WD_CONFIG_TABLE` 中定义。 #### 9. 如何在 WebDynpro 中导航视图 **知识...

    Questions-and-Answers

    8. 浮动元素的使用方法、可能出现的问题及其解决策略。 9. HTML与XHTML的区别,并根据自己的理解决定应该使用哪一个。 10. JSON的作用和用途,以及设计良好的JSON结构。 前端开发的广度和深度决定了它是一个既要求...

    SAP CRM interview questions and answers

    根据提供的文件信息,我们可以深入探讨SAP CRM领域的一系列关键面试问题及答案,这些问题涵盖了从组织模型、业务伙伴创建到系统集成等多个方面。下面将详细解释这些知识点。 ### 组织模型 **问题:** ...

    pku acm 2371 Questions and answers代码

    pku acm 2371 Questions and answers代码 采用二叉查找树排序,解题报告请访问:http://blog.csdn.net/china8848

    Vi and Vim: Questions and Answers

    Vi and Vim: Questions and Answers takes some of the best questions and answers asked on the vi.stackexchange.com website. You can use this book to look up commonly asked questions, browse questions ...

    CISM Review Questions, Answers -amp- Explanations Manual 9th

    《CISM Review Questions, Answers -amp- Explanations Manual 9th》是ISACA认证CISM(Certified Information Security Manager)考试的重要参考资料,它包含了针对CISM考试的全面复习问题、答案以及详尽的解释。...

    Vue.js interview questions and answers in 2023.docx

    8. Vue.js 组件 Vue.js 组件是 Vue.js 应用程序的基本构成单位。每个组件都可以包含模板、脚本和样式。组件可以嵌套使用,实现复杂的 UI 布局。 9. Vue.js 模板 Vue.js 模板是组件的视图层,用于描述组件的 UI ...

    ASP.NET MVC Interview Questions & Answers.pdf

    This book covers useful Interview Questions and Answers on ASP.NET MVC. This book is appropriate for novice as well as for senior level professionals who wants to strengthen their skills before ...

Global site tag (gtag.js) - Google Analytics