Python Pyramid 简明教程
Python Pyramid - Sessions
会话是客户端登录到服务器和注销服务器之间的时间间隔。会话对象也是一个包含会话变量和相关值的键值对的字典对象。在 Pyramid 中,它可用作请求对象的属性。
A session is a time interval between client logs into a server and it logs out of it. Session object is also a dictionary object containing key-value pairs of session variables and associated values. In Pyramid, it is available as an attribute of request object.
为了处理会话机制,必须使用返回会话对象的会话工厂来配置 Pyramid 应用程序对象。Pyramid 内核提供了一个基本会话工厂,它使用 cookie 来存储会话信息。
In order to handle session mechanism, the Pyramid Application object must be configured with a session factory that returns the session object. Pyramid core provides a basic session factory, which uses cookies to store session information.
Default Session Factory
@ {s0}
模块定义了 @ {s1}
类。它的对象需要一个私钥,用于对会话 Cookie 信息进行数字签名。
The pyramid.session module defines SignedCookieSessionFactory class. Its object needs a secret key for digitally signing the session cookie information.
from pyramid.session import SignedCookieSessionFactory
my_session_factory = SignedCookieSessionFactory('abcQWE123!@#')
Configurator
类的 @ {s2}
方法使用此工厂对象来设置会话。
The set_session_factory() method of the Configurator class uses this factory object to set up the session.
config.set_session_factory(my_session_factory)
完成后,会话对象现可用作 @ {s3}
属性进行实现。要添加会话变量,请使用 -
Once this is done, the session object is now available for implementation as request.session attribute. To add a session variable, use −
request.session['user'] = 'Admin'
要检索会话变量,请使用 -
To retrieve a session variable, use −
user=request.session['user']
要移除会话变量,请使用 @ {s4}
方法。
To remove a session variable, use the pop() method.
request.session.pop('user')
Session Example
下面介绍了在 Pyramid 应用程序中使用会话变量。首先,登录路由(与 login()
视图函数相关联)在浏览器上显示登录表单。
Described below is the usage of session variable in a Pyramid application. First, the login route (associated with login() view function) brings up a login form on the browser.
@view_config(route_name='login')
def login(request):
html="""
<html>
<body>
<form action='/add'> Enter User name :
<input type='text' name='user'>
<input type='submit' value='submit'>
</form>
</body>
</html>
"""
return Response(html)
add()
函数读取“用户”表单属性并使用其值添加会话变量。
The add() function reads the 'user' form attribute and uses its value to add a session variable.
@view_config(route_name='addsession')
def add(request):
request.session['user']=request.params['user']
return Response("<h2>Session object added.</h2><br><h3><a href='/read'>click here</a></h3>")
read()
视图读回会话变量数据并显示欢迎消息。
The read() view reads back the session variable data and displays a welcome message.
@view_config(route_name='readsession')
def read(request):
user=request.session['user']
response="<h2>Welcome {} </h2>".format(user)+"<br><h3><a href='/logout'>Logout</a></h3>"
return Response(response)
这些视图和会话工厂添加到应用程序配置中。
These views along with the session factory are added in the application configuration.
config.set_session_factory(my_session_factory)
config.add_route('login','/')
config.add_route('logout','/logout')
config.add_route('addsession', '/add')
config.add_route('readsession', '/read')
config.scan('session')
Example
以下是完整代码 −
The complete code is given below −
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.session import SignedCookieSessionFactory
my_session_factory = SignedCookieSessionFactory('abcQWE123!@#')
@view_config(route_name='login')
def login(request):
html="""
<html>
<body>
<form action='/add'>
Enter User name :
<input type='text' name='user'>
<input type='submit' value='submit'>
</form>
</body>
</html>
"""
return Response(html)
@view_config(route_name='addsession')
def add(request):
request.session['user']=request.params['user']
return Response("<h2>Session object added.</h2><br><h3><a href='/read'>click here</a></h3>")
@view_config(route_name='readsession')
def read(request):
user=request.session['user']
response="<h2>Welcome {} </h2>".format(user)+"<br><h3><a href='/logout'>Logout</a>>/<h3>"
return Response(response)
@view_config(route_name='logout')
def logout(request):
request.session.pop('user')
response="<h2>You have been logged out </h2><br><h3><a href='/'>Login</a></h3>"
return Response(response)
if __name__ == '__main__':
with Configurator() as config:
config.set_session_factory(my_session_factory)
config.add_route('login','/')
config.add_route('logout','/logout')
config.add_route('addsession', '/add')
config.add_route('readsession', '/read')
config.scan('session')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
在 Pyramid 虚拟环境文件夹中的子文件夹(称为“会话”)中将此脚本另存为 main.py
。请注意,此子文件夹必须有一个空 @ {s5}
文件,才能将其视为包。
Save this script as main.py in a subfolder (called 'session') within the Pyramid virtual environment folder. Note that this subfolder must have an empty init.py file for it to be treated as a package.
Output
运行 main.py
并输入 @ {s6}
在浏览器中打开登录表单。
Run main.py and enter http://localhost:6543/ to open up the login form in the browser.
输入用户名并按“提交”按钮。给定的名称将保存为“用户”会话变量。
Enter the user name and press the "submit" button. The given name is saved as a 'user' session variable.
“单击此处”链接读回 @ {s7}
变量并显示欢迎消息。
The 'click here' link reads back the session variable and displays welcome message.
注销链接弹出 @ {s8}
变量并将浏览器带回登录页面。
The logout link pops the session variable and takes the browser back to the login page.