互联网服务供应商
aiohttp-flashbag的Python项目详细描述
库为aiohttp.web提供flashbag。
用法
库允许我们在会话内的请求之间共享一些数据。
基本用法示例:
importaiohttp_flashbagfromaiohttpimportwebfromaiohttp_sessionimportsetupassetup_sessionfromaiohttp_sessionimportSimpleCookieStorageasyncdefhandler_get(request):validation_error=aiohttp_flashbag.flashbag_get(request,'error')error_html=''ifvalidation_errorisnotNone: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)returnweb.Response(body=body.encode('utf-8'),content_type='text/html')asyncdefhandler_post(request):post=awaitrequest.post()iflen(post['name'])==0:aiohttp_flashbag.flashbag_set(request,'error','Name is required')returnweb.HTTPSeeOther('/')body='Hello, {name}'.format(name=post['name'])returnweb.Response(body=body.encode('utf-8'),content_type='text/html')defmake_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,)returnappweb.run_app(make_app())
首先,您必须在aiohttp.web.Application中注册aiohttp_flashbag.flashbag_middleware。
您可以使用aiohttp_flashbag.flashbag_get方法从上一个请求中获取一些数据。参数:
- 请求。aiohttp.web_request.Request的实例。
- 键。要获取的“变量”的名称
- 默认值。如果在会话闪存中不存在密钥,则应该返回默认值。
要在flashbag中设置一个“变量”,应该使用aiohttp_flashbag.flashbag_set。参数:
- 请求。aiohttp.web_request.Request的实例。
- 键。要指定的“变量”的名称。
- 值。要指定的数据。
如果需要替换flashbag中的所有“变量”,则应使用aiohttp_flashbag.flashbag_replace_all。参数:
- 请求。aiohttp.web_request.Request的实例。
- 值。使用要添加到flashbag中的值进行dict。