Skip to main content

Pluggable session support for Starlette.

Project description

Pluggable session support for Starlette and FastAPI frameworks

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

Installation

Install starsessions using PIP or poetry:

pip install starsessions
# or
poetry add starsessions

Use redis extra for Redis support.

Quick start

See example application in examples/ 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

Memory

Class: starsessions.InMemoryBackend

Simply stores data in memory. The data is cleared after server restart. Mostly for use with unit tests.

CookieBackend

Class: starsessions.CookieBackend

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

Redis

Class: starsessions.backends.redis.RedisBackend

Requires aioredis, use pip install starsessions[redis] or poetry add starsessions[redis]

Stores session data in a Redis server. The backend accepts either connection URL or an instance of aioredis.Redis.

import aioredis
from starsessions.backends.redis import RedisBackend

backend = RedisBackend('redis://localhost')
# or
redis = aioredis.from_url('redis://localhost')

backend = RedisBackend(connection=redis)

Custom backend

Creating new backends is quite simple. All you need is to extend starsessions.SessionBackend class and implement abstract methods.

Here is an example of how we can create a memory-based session backend. Note, it is important that write method returns session ID as a string value.

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

Serializers

Sometimes you cannot pass raw session data to the backend. The data must be serialized into something the backend can handle.

Some backends (like RedisBackend) optionally accept serializer argument that will be used to serialize and deserialize session data. By default, we provide (and use) starsessions.JsonSerializer but you can implement your own by extending starsessions.Serializer class.

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.1.0.tar.gz (9.0 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.1.0-py3-none-any.whl (9.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: starsessions-1.1.0.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.8 CPython/3.9.6 Linux/5.8.0-1040-azure

File hashes

Hashes for starsessions-1.1.0.tar.gz
Algorithm Hash digest
SHA256 2181f33d8499bbc31e5fe9bcb5d55daf1e26d68b5423f90fd4848b4827ff3afb
MD5 d64194fb1ea1ef7e41056c634a765c7f
BLAKE2b-256 afdba096a8817dfe9e177656a477f4d7dfd5bfe88e5a9522c49f5f0b9f75bd14

See more details on using hashes here.

File details

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

File metadata

  • Download URL: starsessions-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 9.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.8 CPython/3.9.6 Linux/5.8.0-1040-azure

File hashes

Hashes for starsessions-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ffb4b79b15df1f81f610d2a8ebe7ee4b77f70fefd30fdbb36d6fe62468ec857d
MD5 d07a70cc705462d3e123b2f069b9c79d
BLAKE2b-256 cd950a3897a0e048c27ae7aee15799fd7d9df1e5d6e73e86c9aab0eba0916434

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