Skip to main content

Signed Cookie-Based HTTP sessions for ASGI applications

Project description

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

Tests Status PYPI Version Python Versions

Features

  • Supports base64 sessions

  • Supports JWT signed sessions

  • Supports Fernet encrypted sessions

Requirements

  • python >= 3.9

Installation

asgi-sessions should be installed using pip:

pip install asgi-sessions

To install optional JWT, Fernet support:

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

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, session_type='jwt', 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(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

Options

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,

)

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-1.2.3.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

asgi_sessions-1.2.3-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file asgi_sessions-1.2.3.tar.gz.

File metadata

  • Download URL: asgi_sessions-1.2.3.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.9.19

File hashes

Hashes for asgi_sessions-1.2.3.tar.gz
Algorithm Hash digest
SHA256 4ae1cfeac86fba8f9da9c79e959ca3ff7d150737b6313fcf20a017a16eb52443
MD5 81b53469f62dddf6dd0c630d58544469
BLAKE2b-256 81dee6b743261e11f092f8b129e2d45653d023adf3606e9beab3884a353ea882

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for asgi_sessions-1.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 1575609dcc5b5619dc8c3fa746c9d57a04f2a1d75f19f94e5a3810f2b56c812b
MD5 4da75012d8adb6ea4e6554630b545b81
BLAKE2b-256 cb2cd121dff670ef886a7199ce3402c53a3d69207652ba4a8421eb6ebca419ba

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