跳转到主要内容

基于Cookie的ASGI应用的HTTP会话

项目描述

asgi-sessions – 基于Cookie的ASGI应用的HTTP会话(Asyncio / Trio, / Curio

Tests Status PYPI Version Python Versions

特性

  • 支持base64会话

  • 支持JWT签名会话

  • 支持Fernet加密会话

要求

  • python >= 3.9

安装

asgi-sessions 应使用pip安装

pip install asgi-sessions

要安装可选JWT, Fernet支持

pip install asgi-sessions[jwt]
pip install asgi-sessions[fernet]

使用

常见ASGI应用

from asgi_sessions import SessionMiddleware


async def my_app(scope, receive, send):
    """Read session and get the current user data from it or from request query."""
    # The middleware puts a session into scope['session]
    session = scope['session']

    status, headers = 200, []
    if scope['query_string']:
        # Store any information inside the session
        session['user'] = scope['query_string'].decode()
        status, headers = 307, [(b"location", b"/")]

    # Read a stored info from the session
    user = (session.get('user') or 'anonymous').title().encode()

    await send({"type": "http.response.start", "status": status, "headers": headers})
    await send({"type": "http.response.body", "body": b"Hello %s" % user})

app = SessionMiddleware(my_app, session_type='jwt', secret_key="sessions-secret")

# http GET / -> Hello Anonymous
# http GET /?tom -> Hello Tom
# http GET / -> Hello Tom

作为ASGI-Tools内部中间件

from asgi_tools import App
from asgi_sessions import SessionMiddleware

app = App()
app.middleware(SessionMiddleware.setup(session_type='jwt', secret_key='SESSION-SECRET'))

@app.route('/')
async def index(request):
    user = request.session.get('user', 'Anonymous')
    return 'Hello %s' % user.title()

@app.route('/login/{user}')
async def login(request):
    request.session['user'] = request.path_params.get('user', 'Anonymous')
    return 'Done'

@app.route('/logout')
async def logout(request, *args):
    del request.session['user']
    return 'Done'

# http GET / -> Hello Anonymous
# http GET /login/tom -> Done
# http GET / -> Hello Tom
# http GET /logout -> Done
# http GET / -> Hello Anonymous

选项

from asgi_sessions import SessionMiddleware

app = SessionMiddleware(

     # Your ASGI application
     app,

     # Session type (base64|jwt|fernet)
     session_type="base64",

     # Secret Key for the session (required for JWT/Fernet sessions)
     secret_key=None,

     # Cookie name to keep the session (optional)
     cookie_name='session',

     # Cookie max age (in seconds) (optional)
     max_age=14 * 24 * 3600,

     # Cookie samesite (optional)  # Python 3.8+ only
     samesite='lax',

     # Cookie secure (https only) (optional)
     secure=False,

)

错误追踪器

如果您有任何建议、错误报告或烦恼,请向https://github.com/klen/asgi-sessions/issues的问题跟踪器报告

贡献

项目开发发生在:https://github.com/klen/asgi-sessions

许可协议

遵循MIT许可证

项目详情


下载文件

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

源码分发

asgi_sessions-1.2.4.tar.gz (6.3 kB 查看哈希值)

上传时间: 源码

构建分发

asgi_sessions-1.2.4-py3-none-any.whl (6.2 kB 查看哈希值)

上传时间: Python 3

由以下组织支持