Pyramid 消息闪现

2023-03-30 17:45 更新

消息闪烁的机制被Web应用程序框架用来向用户提供关于他与应用程序交互的某些反馈。闪现的消息被会话对象保存在一个队列中。

闪现消息机制使得在一个视图中创建一个消息并在下一个调用的视图函数中渲染它成为可能。正如上一节所述,我们必须先启用会话工厂,以便能够处理会话。要在消息队列中添加一条消息,请使用会话对象的 flash() 方法。

request.session.flash('Hello World')

会话有 pop_flash() 和 peek_flash() 方法。pop_flash()方法从队列中删除最后添加的消息。peek_flash()方法在队列中有消息时返回true,如果是空的则返回false。

这两个方法在模板网页中都是用来从队列中获取一条或几条消息,并将其作为响应的一部分呈现。

消息闪现示例

下面的例子展示了消息闪现的机制。这里,login()视图代码检查它是否被POST或GET方法调用。如果方法是GET,它将渲染带有用户名和密码字段的登录表单。提交的表单会以POST方式提交到同一个URL。

当检测到POST方法时,视图会进一步检查输入的有效性,并向会话队列闪现适当的信息。这些错误的闪光信息是由登录模板本身提取的,而在成功的闪光信息闪烁之后,客户端被重定向到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的虚拟环境中的flash子文件夹中,并在其中放入一个空白的 __init__.py 。将两个模板(”index.html “和 “login.html”)保存在 flush/templates 文件夹中。

输出

运行main.py,通过点击 http://localhost:6543/login ,在浏览器中打开登录表单。

Python Pyramid - 消息闪现

尝试输入一个保留的用户名 “admin”、”manager “或 “supervisor”。错误信息将被闪现,如下图所示 –

Python Pyramid - 消息闪现

这一次,输入可接受的凭证,看看结果 –

Python Pyramid - 消息闪现



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号