为aiohttp.web提供Flashbag(闪存消息)支持
项目描述
该库为aiohttp.web提供闪存袋。
用法
该库允许我们在会话内部请求之间共享一些数据。
基本用法示例
import aiohttp_flashbag
from aiohttp import web
from aiohttp_session import setup as setup_session
from aiohttp_session import SimpleCookieStorage
async def handler_get(request):
validation_error = aiohttp_flashbag.flashbag_get(request, 'error')
error_html = ''
if validation_error is not None:
error_html = '<span>{validation_error}</span>'.format(
validation_error=validation_error,
)
body = '''
<html>
<head><title>aiohttp_flashbag demo</title></head>
<body>
<form method="POST" action="/">
<input type="text" name="name" />
{error_html}
<input type="submit" value="Say hello">
</form>
</body>
</html>
'''
body = body.format(error_html=error_html)
return web.Response(body=body.encode('utf-8'), content_type='text/html')
async def handler_post(request):
post = await request.post()
if len(post['name']) == 0:
aiohttp_flashbag.flashbag_set(request, 'error', 'Name is required')
return web.HTTPSeeOther('/')
body = 'Hello, {name}'.format(name=post['name'])
return web.Response(body=body.encode('utf-8'), content_type='text/html')
def make_app():
session_storage = SimpleCookieStorage()
app = web.Application()
setup_session(app, session_storage)
app.middlewares.append(aiohttp_flashbag.flashbag_middleware)
app.router.add_route(
'GET',
'/',
handler_get,
)
app.router.add_route(
'POST',
'/',
handler_post,
)
return app
web.run_app(make_app())
首先,您必须在aiohttp.web.Application中注册aiohttp_flashbag.flashbag_middleware。
您可以使用aiohttp_flashbag.flashbag_get方法从先前的请求中获取一些数据。参数
request. aiohttp.web_request.Request实例。
key. 您想要获取的“变量”的名称
default. 如果在会话闪存袋中不存在该键,应返回的默认值。
要设置闪存袋中的一个“变量”,您应该使用aiohttp_flashbag.flashbag_set。参数
request. aiohttp.web_request.Request实例。
key. 您想要指定的“变量”的名称。
value. 您想要指定的数据。
如果您需要替换闪存袋中的所有“变量”,您应该使用aiohttp_flashbag.flashbag_replace_all。参数
request. aiohttp.web_request.Request实例。
value. 包含您想要添加到闪存袋中的值的字典。