跳转到主要内容

为aiohttp.web提供Flashbag(闪存消息)支持

项目描述

该库为aiohttp.web提供闪存袋。

https://img.shields.io/travis/aio-libs/aiohttp-flashbag.svg https://codecov.io/github/aio-libs/aiohttp-flashbag/coverage.svg

用法

该库允许我们在会话内部请求之间共享一些数据。

基本用法示例

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。参数

如果您需要替换闪存袋中的所有“变量”,您应该使用aiohttp_flashbag.flashbag_replace_all。参数

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

aiohttp-flashbag-0.0.3.tar.gz (3.4 kB 查看哈希值)

上传时间

构建分发

aiohttp_flashbag-0.0.3-py3-none-any.whl (3.1 kB 查看哈希值)

上传时间 Python 3

支持