Skip to content


BlackSheep implements built-in support for sessions, which are handled through digitally signed cookies. This page describes how to use sessions with the built-in classes.

🚀 Added in version 1.0.1

Enabling sessions

To enable sessions, use the app.use_sessions method as in the example below:

from blacksheep.messages import Request
from blacksheep.server import Application
from blacksheep.server.responses import text

app = Application()


def home(request: Request):
    session = request.session

    session["example"] = "Lorem ipsum"

    return text(session["example"])

The use_sessions method accepts the following parameters:

Name Description Defaults to
secret_key required secret key used for signing N/A
session_cookie optional session cookie name "session"
serializer optional blacksheep.sessions.Serializer to serialize and deserialize session values blacksheep.sessions.JSONSerializer
signer optional itsdangerous.Signer to sign the session cookie itsdangerous.TimestampSigner
encryptor optional blacksheep.sessions.Encryptor to encrypt the session cookie None
session_max_age Optional session max age, in seconds None
    def use_sessions(
        secret_key: str,
        session_cookie: str = "session",
        serializer: Optional[SessionSerializer] = None,
        signer: Optional[Signer] = None,
        encryptor: Optional[Encryptor] = None,
        session_max_age: Optional[int] = None,
    ) -> None:

The built-in sessions middleware uses itsdangerous to sign and verify session cookies.

Using sessions

When sessions are enabled, they are always populated for the request object, and can be accessed through the request.session property.

The sessions middleware takes care of setting a response cookie whenever the session is modified.

def home(request: Request):
    session = request.session

    # setting a value
    session["example"] = "Lorem ipsum"

    # getting a value
    foo = session.get("foo")

    # getting a value with default
    foo = session.get("foo", 100)

    # getting a value (can produce KeyError)
    foo = session["foo"]

    # checking if a key is set
    if "something" in session:

    # deleting a key
    del session["something"]

    # update with many values
    session.update({"a": 1, "b": 2})

    return text(session["example"])

Enabling encryption

By default, session cookies are only signed but not encrypted. This paragraph describes how to enable encryption of session cookies.

To use the built-in solution for session cookies encryption, install this extra dependency:

pip install cryptography==3.4.6

Note: it is also possible to install blacksheep using this command: pip install blacksheep[full] to include extra dependencies

from blacksheep.messages import Request
from blacksheep.server import Application
from blacksheep.server.responses import text, pretty_json
from blacksheep.sessions.crypto import FernetEncryptor
from cryptography.fernet import Fernet

app = Application()

# TODO: store the keys in app settings, in the preferred way, and use them to configure
# sessions
# NOTE: do not generate a new encryption key at each application restart, otherwise
# all sessions are invalidated if the application is restarted!
signing_key = "<SIGNING_KEY>"
encryption_key = Fernet.generate_key()

app.use_sessions("<SIGNING_KEY>", encryptor=FernetEncryptor(encryption_key))

def home(request: Request):
    session = request.session

    session["example"] = "Lorem ipsum"

    if "count" in session:
        session["count"] = session["count"] + 1
        session["count"] = 0

    return text(session["example"])

def test(request: Request):
    session = request.session

    if "example" not in session:
        return text("First visit the path /")

    return pretty_json(session.to_dict())