Skip to main content

Signed Cookie-Based HTTP sessions for ASGI applications

Project description

asgi-sessions – Signed Cookie-Based HTTP sessions for ASGI applications (Asyncio / Trio, / Curio)

Tests Status PYPI Version Python Versions

Requirements

  • python >= 3.7

Installation

asgi-sessions should be installed using pip:

pip install asgi-sessions

Usage

Common ASGI applications:

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, secret_key="sessions-secret")

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

As ASGI-Tools Internal middleware

from asgi_tools import App
from asgi_sessions import SessionMiddleware

app = App()
app.middleware(SessionMiddleware.setup(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

Options

from asgi_sessions import SessionMiddleware

app = SessionMiddleware(

     # Your ASGI application
     app,

     # Secret Key for the session (required)
     secret_key,

     # 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,

)

Bug tracker

If you have any suggestions, bug reports or annoyances please report them to the issue tracker at https://github.com/klen/asgi-sessions/issues

Contributing

Development of the project happens at: https://github.com/klen/asgi-sessions

License

Licensed under a MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

asgi-sessions-0.9.0.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

asgi_sessions-0.9.0-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file asgi-sessions-0.9.0.tar.gz.

File metadata

  • Download URL: asgi-sessions-0.9.0.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

File hashes

Hashes for asgi-sessions-0.9.0.tar.gz
Algorithm Hash digest
SHA256 0aa65d633fc383f726ddf02ba9b42ef2e12b9a3d2053c5b9d4d16b482d9547e0
MD5 04074974c5e9d1503ab82ca641c18473
BLAKE2b-256 ae10f8b4c719a7d563bae455b39a3fd4b4f02acb70964bb613e0e61f4df3cb8b

See more details on using hashes here.

File details

Details for the file asgi_sessions-0.9.0-py3-none-any.whl.

File metadata

  • Download URL: asgi_sessions-0.9.0-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

File hashes

Hashes for asgi_sessions-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1cb568f8bee8237d26817211c6aff0b7a9ec74a05c1da3e9b576e06b8afa52bb
MD5 71495e56c7187a3ab48897ec9c066b06
BLAKE2b-256 5540e04471af90bacf0a57677a78dd91aacfcca3a04c946f09ce315fd3758ab0

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page