Pyramid 消息閃現(xiàn)

2023-03-30 17:45 更新

消息閃爍的機(jī)制被Web應(yīng)用程序框架用來(lái)向用戶(hù)提供關(guān)于他與應(yīng)用程序交互的某些反饋。閃現(xiàn)的消息被會(huì)話對(duì)象保存在一個(gè)隊(duì)列中。

閃現(xiàn)消息機(jī)制使得在一個(gè)視圖中創(chuàng)建一個(gè)消息并在下一個(gè)調(diào)用的視圖函數(shù)中渲染它成為可能。正如上一節(jié)所述,我們必須先啟用會(huì)話工廠,以便能夠處理會(huì)話。要在消息隊(duì)列中添加一條消息,請(qǐng)使用會(huì)話對(duì)象的 flash() 方法。

request.session.flash('Hello World')

會(huì)話有 pop_flash() 和 peek_flash() 方法。pop_flash()方法從隊(duì)列中刪除最后添加的消息。peek_flash()方法在隊(duì)列中有消息時(shí)返回true,如果是空的則返回false。

這兩個(gè)方法在模板網(wǎng)頁(yè)中都是用來(lái)從隊(duì)列中獲取一條或幾條消息,并將其作為響應(yīng)的一部分呈現(xiàn)。

消息閃現(xiàn)示例

下面的例子展示了消息閃現(xiàn)的機(jī)制。這里,login()視圖代碼檢查它是否被POST或GET方法調(diào)用。如果方法是GET,它將渲染帶有用戶(hù)名和密碼字段的登錄表單。提交的表單會(huì)以POST方式提交到同一個(gè)URL。

當(dāng)檢測(cè)到POST方法時(shí),視圖會(huì)進(jìn)一步檢查輸入的有效性,并向會(huì)話隊(duì)列閃現(xiàn)適當(dāng)?shù)男畔ⅰ_@些錯(cuò)誤的閃光信息是由登錄模板本身提取的,而在成功的閃光信息閃爍之后,客戶(hù)端被重定向到index()視圖來(lái)渲染索引模板。

應(yīng)用程序代碼中的兩個(gè)視圖是–

@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模板代碼遍歷消息隊(duì)列,在 **< div id=’flash’> **部分彈出每個(gè)消息。

下面是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>

例子

本例的應(yīng)用代碼為 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子文件夾中,并在其中放入一個(gè)空白的 __init__.py 。將兩個(gè)模板(”index.html “和 “l(fā)ogin.html”)保存在 flush/templates 文件夾中。

輸出

運(yùn)行main.py,通過(guò)點(diǎn)擊 http://localhost:6543/login ,在瀏覽器中打開(kāi)登錄表單。

Python Pyramid - 消息閃現(xiàn)

嘗試輸入一個(gè)保留的用戶(hù)名 “admin”、”manager “或 “supervisor”。錯(cuò)誤信息將被閃現(xiàn),如下圖所示 –

Python Pyramid - 消息閃現(xiàn)

這一次,輸入可接受的憑證,看看結(jié)果 –

Python Pyramid - 消息閃現(xiàn)



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)