消息閃爍的機制被Web應用程序框架用來向用戶提供關于他與應用程序交互的某些反饋。閃現(xiàn)的消息被會話對象保存在一個隊列中。
閃現(xiàn)消息機制使得在一個視圖中創(chuàng)建一個消息并在下一個調用的視圖函數(shù)中渲染它成為可能。正如上一節(jié)所述,我們必須先啟用會話工廠,以便能夠處理會話。要在消息隊列中添加一條消息,請使用會話對象的 flash() 方法。
request.session.flash('Hello World')
會話有 pop_flash() 和 peek_flash() 方法。pop_flash()方法從隊列中刪除最后添加的消息。peek_flash()方法在隊列中有消息時返回true,如果是空的則返回false。
這兩個方法在模板網(wǎng)頁中都是用來從隊列中獲取一條或幾條消息,并將其作為響應的一部分呈現(xiàn)。
消息閃現(xiàn)示例
下面的例子展示了消息閃現(xiàn)的機制。這里,login()視圖代碼檢查它是否被POST或GET方法調用。如果方法是GET,它將渲染帶有用戶名和密碼字段的登錄表單。提交的表單會以POST方式提交到同一個URL。
當檢測到POST方法時,視圖會進一步檢查輸入的有效性,并向會話隊列閃現(xiàn)適當?shù)男畔?。這些錯誤的閃光信息是由登錄模板本身提取的,而在成功的閃光信息閃爍之后,客戶端被重定向到index()視圖來渲染索引模板。
應用程序代碼中的兩個視圖是–
@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模板有以下代碼 —
<!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’> **部分彈出每個消息。
下面是index.html的腳本,它顯示由login()視圖插入的成功消息 ?
<!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>
例子
本例的應用代碼為 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的虛擬環(huán)境中的flash子文件夾中,并在其中放入一個空白的 __init__.py 。將兩個模板(”index.html “和 “l(fā)ogin.html”)保存在 flush/templates 文件夾中。
輸出
運行main.py,通過點擊 http://localhost:6543/login ,在瀏覽器中打開登錄表單。
嘗試輸入一個保留的用戶名 “admin”、”manager “或 “supervisor”。錯誤信息將被閃現(xiàn),如下圖所示 –
這一次,輸入可接受的憑證,看看結果 –
更多建議: