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)

Tests Status PYPI Version

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):
    session = request['session']
    user = session.get('user', 'Anonymous')
    return 'Hello %s' % user.title()

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

@app.route('/logout')
async def logout(request, *args):
    session = request['session']
    del 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)
     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 Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

asgi_sessions-0.3.0-py3-none-any.whl (4.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: asgi_sessions-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 4.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.9.0

File hashes

Hashes for asgi_sessions-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c5d6dd9a33577f7f1ffb456ce5eb075307bea1604eb9762b25da277aebf67648
MD5 13216adeebba7babd7fe8f93e7c6167b
BLAKE2b-256 45257c4228be7da935d3fd701bb1985faf7fcce10579aeb65ea992ce0f33eb8f

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