Python Pyramid 简明教程
Python Pyramid - Message Flashing
消息闪现机制由 Web 应用程序框架用于向用户提供有关其与应用程序交互的特定反馈。闪现消息由会话对象保存在队列中。
The mechanism of message flashing is used by web application frameworks to provide certain feedback to the user about his interaction with the application. The flashed messages are held in a queue by the session object.
闪现消息机制允许在某个视图中创建消息并在称作下一视图的视图函数中呈现消息。与前一节一样,我们必须首先启用会话工厂才能处理会话。要向消息队列中添加消息,请使用会话对象的 flash() 方法。
Flash messaging mechanism makes it possible to create a message in one view and render it in a view function called next. As in the previous section, we must enable the session factory first to be able to handle the session. To add a message in the message queue, use flash() method of the session object.
request.session.flash('Hello World')
该会话具有 pop_flash() 和 peek_flash() 方法。pop_flash() 方法从队列中移除最近添加的消息。peek_flash() 方法在队列中有消息时返回 true,在队列为空时返回 false。
The session has pop_flash() and peek_flash() methods. The pop_flash() method removes the last added message from the queue. The peek_flash() method returns true if the queue has a message, false if it is empty.
这两个方法都在一个模板 Web 页面中使用,用于从队列中提取一条或多条消息并将其作为响应的一部分进行呈现。
Both these methods are used in a template web page to fetch one or messages from the queue and render it as a part of the response.
Message Flashing Example
以下示例演示了消息闪现机制。此处的 login() 视图代码检查是否已通过 POST 或 GET 方法调用它。如果该方法是 GET,它将呈现带有用户名和密码字段的登录表单。提交的表单将通过 POST 方法提交到同一个 URL。
The mechanism of message flashing is demonstrated by the example below. Here, the login() view code checks if it has been invoked by POST or GET method. If the method is GET, it renders the login form with username and password fields. The submitted form is submitted with POST method to the same URL.
当检测到 POST 方法时,视图进一步检查输入的有效性并在会话队列中闪现适当的消息。这些错误闪现消息由登录模板本身提取,而在成功闪现消息被闪现后,客户端被重定向到 index() 视图,以呈现 index 模板。
When the POST method is detected, the view further checks the validity of the inputs and flashes appropriate messages to the session queue. These error flash messages are extracted by the login template itself, whereas after the success flash message is flashed, the client is redirected to the index() view to render the index template.
应用程序代码中的两个视图是 −
The two views in the application code are −
@view_config(route_name='login', renderer='templates/login.html')
def login(request):
if request.method == 'POST':
if request.POST['password']=='' or request.POST['username']=='':
request.session.flash('User name and password is required')
return HTTPFound(location=request.route_url('login'))
if len(request.POST['password'])in range(1,9):
request.session.flash('Weak password!')
if request.POST['username']not in ['admin', 'manager', 'supervisor']:
request.session.flash('successfully logged in!')
return HTTPFound(location=request.route_url('index'))
else:
request.session.flash('Reserved user ID Forbidden!')
return HTTPFound(location=request.route_url('login'))
return {}
@view_config(route_name='index', renderer='templates/index.html')
def index(request):
return {}
login.html 模板具有以下代码 −
The login.html template has the following code −
<!doctype html>
<html>
<head>
<style>
p {background-color:grey; font-size: 150%}
</style>
</head>
<body>
<h1>Pyramid Message Flashing Example</h1>
{% if request.session.peek_flash()%}
<div id="flash">
{% for message in request.session.pop_flash() %}
<p>{{ message }}</p>
{% endfor %}
</div>
{% endif %}
<h3>Login Form</h3>
<form action="" method="POST">
<dl>
<dt>Username:
<dd><input type="text" name="username">
<dt>Password:
<dd><input type="password" name="password">
</dl>
<input type="submit" value="Login">
</form>
</body>
</html>
在显示登录表单之前,jinja2 模板代码遍历消息队列,在 <div id='flash'> 部分中弹出每条消息。
Before the login form is displayed, the jinja2 template code traverses through the message queue, pops each message in the <div id='flash'> section.
以下是在 login() 视图中插入的成功消息 index.html 的脚本 −
Following is the script for index.html that flashes the success messages inserted by the login() view −
<!doctype html>
<html>
<head>
<style>
p {background-color:grey; font-size: 150%}
</style>
</head>
<body>
{% if request.session.peek_flash()%}
<div id="flash">
{% for message in request.session.pop_flash() %}
<p>{{ message }}</p>
{% endfor %}
{% endif %}
<h1>Pyramid Message Flashing Example</h1>
<h3>Do you want to <a href = "/login">
<b>log in?</b></a></h3>
</body>
</html>
Example
此示例的应用程序代码是: main.py
The application code for this example is main.py
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
from pyramid.httpexceptions import HTTPFound
my_session_factory = SignedCookieSessionFactory(' abcQWE123!@#')
@view_config(route_name='login', renderer='templates/login.html')
def login(request):
if request.method == 'POST':
if request.POST['password']=='' or request.POST['username']=='':
request.session.flash('User name and password is required')
return HTTPFound(location=request.route_url('login'))
if len(request.POST['password'])in range(1,9):
request.session.flash('Weak password!')
if request.POST['username']not in ['admin', 'manager', 'supervisor']:
request.session.flash('successfully logged in!')
return HTTPFound(location=request.route_url('index'))
else:
request.session.flash('Reserved user ID Forbidden!')
return HTTPFound(location=request.route_url('login'))
return {}
@view_config(route_name='index', renderer='templates/index.html')
def index(request):
return {}
if __name__ == '__main__':
with Configurator() as config:
config.set_session_factory(my_session_factory)
config.include('pyramid_jinja2')
config.add_jinja2_renderer(".html")
config.add_route('login','/login')
config.add_route('index','/')
config.scan('flash')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
将此程序代码另存为 app.py 在 Pyramid 虚拟环境中的 Flash 子文件夹中,并在其中放置一个 init.py 。将两个模板(“index.html”和“login.html”)存储在 flush\templates 文件夹中。
Save this program code as app.py in a flash subfolder in the virtual environment for Pyramid, putting a blank init.py in it. Store the two templates ("index.html" and "login.html") in flush\templates folder.
Output
运行 main.py,然后单击 http://localhost:6543/login 链接通过浏览器打开登录表单。
Run the main.py and open the login form in the browser by clicking the http://localhost:6543/login link.
尝试输入其中一个保留的用户名“admin”、“manager”或“supervisor”。将闪现错误消息,如下所示:
Try entering one of the reserved usernames 'admin', 'manager', or 'supervisor'. The error message will be flashed as shown below −
此时,输入可接受的凭证并查看结果:
This time, enter acceptable credentials and see the result −