Coder Social home page Coder Social logo

asgi-sessions's Introduction

ASGI-Sessions

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

Tests Status PYPI Version Python Versions
  • Supports base64 sessions
  • Supports JWT signed sessions
  • Supports Fernet encrypted sessions
  • python >= 3.7

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]

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

)

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

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

Licensed under a MIT license.

asgi-sessions's People

Contributors

klen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

nixroxursox

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.