Skip to main content

Pluggable session support for Starlette.

Project description

Pluggable session support for Starlette and FastAPI frameworks

This package based on this long standing pull request into the mainstream by the same author.

Installation

Install starsessions using PIP or poetry:

pip install starsessions
# or
poetry add starsessions

Quick start

See example application in example/ directory of this repository.

Enable session support

In order to enable session support add starsessions.SessionMiddleware to your application.

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starsessions import SessionMiddleware

middleware = [
    Middleware(SessionMiddleware, secret_key='TOP SECRET'),
]

app = Starlette(middleware=middleware, **other_options)

Session autoloading

Note, for performance reasons session won't be autoloaded by default, you need to explicitly call await request.session.load() before accessing the session otherwise SessionNotLoaded exception will be raised. You can change this behavior by passing autoload=True to your middleware settings:

Middleware(SessionMiddleware, secret_key='TOP SECRET', autoload=True)

Default session backend

The default backend is CookieBackend. You don't need to configure it just pass secret_key argument and the backend will be automatically configured for you.

Change default backend

When you want to use a custom session storage then pass a desired backend instance via backend argument of the middleware.

from starlette.applications import Starlette
from starlette.middleware.sessions import SessionMiddleware
from starlette.sessions import CookieBackend

backend = CookieBackend(secret_key='secret', max_age=3600)

app = Starlette()
app.add_middleware(SessionMiddleware, backend=backend)

Built-in backends

InMemoryBackend

Simply stores data in memory. The data is not persisted across requests. Mostly for use with unit tests.

CookieBackend

Stores session data in a signed cookie on the client. This is the default backend.

Custom backend

Create a class which implements the starsessions.SessionBackend interface:

from starlette.sessions import SessionBackend
from typing import Dict

# instance of class which manages session persistence

class InMemoryBackend(SessionBackend):
    def __init__(self):
        self._storage = {}

    async def read(self, session_id: str) -> Dict:
        """ Read session data from a data source using session_id. """
        return self._storage.get(session_id, {})

    async def write(self, data: Dict, session_id: str=None) -> str:
        """ Write session data into data source and return session id. """
        session_id = session_id or await self.generate_id()
        self._storage[session_id] = data
        return session_id

    async def remove(self, session_id: str):
        """ Remove session data. """
        del self._storage[session_id]

    async def exists(self, session_id: str)-> bool:
        return session_id in self._storage

Note, write has to return the session id.

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

starsessions-1.0.1.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

starsessions-1.0.1-py3-none-any.whl (6.4 kB view details)

Uploaded Python 3

File details

Details for the file starsessions-1.0.1.tar.gz.

File metadata

  • Download URL: starsessions-1.0.1.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.6 CPython/3.9.5 Linux/5.8.0-1033-azure

File hashes

Hashes for starsessions-1.0.1.tar.gz
Algorithm Hash digest
SHA256 bd535082b1bc507e106b864cc378d646dcafd301f59efe6a52dfd2c4ac766e75
MD5 ee2f35cccf05041f53a10c2126cc92d7
BLAKE2b-256 3726381df22e823b79fba1d806230723961244de9250c57f60e55897c8b37a70

See more details on using hashes here.

File details

Details for the file starsessions-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: starsessions-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 6.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.6 CPython/3.9.5 Linux/5.8.0-1033-azure

File hashes

Hashes for starsessions-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 805eb57a2968681d079e9d51fa9638912d398688a459308ed0cd17b8f10323f2
MD5 6dd7b59d8cab67a46026e019d57d42af
BLAKE2b-256 66e7629d21e2cde95c7a91dccb83427bddbb51db5fe899d704ca0af8071ad44a

See more details on using hashes here.

Supported by

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