Skip to content

Usage

Using the package is actually very simple since it is prepared to handle the way Esmerald works, so it fits withihn your application in the same way you add any other middleware to the application.

How to use it

There are many ways you can plug Esmerald Sessions into your application. For the examples, let us use Redis.

Within the instantiation

Esmerald being a system that is versatile allows you to add the middleware within the application instance.

from esmerald import Esmerald, Gateway, get, post
from esmerald.requests import Request
from esmerald.responses import JSONResponse
from esmerald.utils.crypto import get_random_secret_key
from redis import Redis
from starlette.middleware import Middleware

from esmerald_sessions import SessionConfig, SessionMiddleware
from esmerald_sessions.enums import BackendType


@get()
async def view_session(request: Request) -> JSONResponse:
    return JSONResponse({"session": request.session})


@post()
async def setup_session(request: Request) -> JSONResponse:
    request.session.update({"data": "session.data"})
    return JSONResponse({"session": request.session})


@post()
async def clear_session(request: Request) -> JSONResponse:
    request.session.clear()
    return JSONResponse({"session": request.session})


redis_client = Redis(host="localhost", port=6379)
session_config = SessionConfig(
    secret_key=get_random_secret_key(),
    cookie_name="cookie",
    backend_type=BackendType.redis,
    backend_client=redis_client,
)

app = Esmerald(
    routes=[
        Gateway("/view-session", handler=view_session),
        Gateway("/setup-session", handler=setup_session),
        Gateway("/clear-session", handler=clear_session),
    ],
    middleware=[Middleware(SessionMiddleware, config=session_config)],
)

Using add_middleware

You can also add the middleware in the classic and sometimes familiar way as well.

from esmerald import Esmerald, Gateway, get, post
from esmerald.requests import Request
from esmerald.responses import JSONResponse
from esmerald.utils.crypto import get_random_secret_key
from redis import Redis

from esmerald_sessions import SessionConfig, SessionMiddleware
from esmerald_sessions.enums import BackendType


@get()
async def view_session(request: Request) -> JSONResponse:
    return JSONResponse({"session": request.session})


@post()
async def setup_session(request: Request) -> JSONResponse:
    request.session.update({"data": "session.data"})
    return JSONResponse({"session": request.session})


@post()
async def clear_session(request: Request) -> JSONResponse:
    request.session.clear()
    return JSONResponse({"session": request.session})


redis_client = Redis(host="localhost", port=6379)
session_config = SessionConfig(
    secret_key=get_random_secret_key(),
    cookie_name="cookie",
    backend_type=BackendType.redis,
    backend_client=redis_client,
)

app = Esmerald(
    routes=[
        Gateway("/view-session", handler=view_session),
        Gateway("/setup-session", handler=setup_session),
        Gateway("/clear-session", handler=clear_session),
    ],
)

app.add_middleware(SessionMiddleware, config=session_config)

Using the settings

The Esmerald settings system makes this process even cleaner for your application.

Let's create the settings.

settings.py
from typing import List

from esmerald import EsmeraldAPISettings
from esmerald.types import Middleware
from esmerald.utils.crypto import get_random_secret_key
from redis import Redis

from esmerald_sessions import BackendType, SessionConfig, SessionMiddleware


class AppSettings(EsmeraldAPISettings):
    secret_key: str = get_random_secret_key()

    @property
    def session_config(self) -> SessionConfig:
        redis = Redis(host="localhost", port=6379)
        return SessionConfig(
            secret_key=self.secret_key,
            cookie_name="cookie",
            backend_type=BackendType.redis,
            backend_client=redis,
        )

    @property
    def middleware(self) -> List["Middleware"]:
        session_middleware = Middleware(SessionMiddleware, config=self.session_config)
        return [session_middleware]

Now let's create the application in a main.py.

main.py
from esmerald import Esmerald, Gateway, get, post
from esmerald.requests import Request
from esmerald.responses import JSONResponse


@get()
async def view_session(request: Request) -> JSONResponse:
    return JSONResponse({"session": request.session})


@post()
async def setup_session(request: Request) -> JSONResponse:
    request.session.update({"data": "session.data"})
    return JSONResponse({"session": request.session})


@post()
async def clear_session(request: Request) -> JSONResponse:
    request.session.clear()
    return JSONResponse({"session": request.session})


app = Esmerald(
    routes=[
        Gateway("/view-session", handler=view_session),
        Gateway("/setup-session", handler=setup_session),
        Gateway("/clear-session", handler=clear_session),
    ],
)

Now let's start the application.

ESMERALD_SETTINGS_MODULE=settings.AppSettings python -m main:app

Check

Because Esmerald works really well with settings and uses the ESMERALD_SETTINGS_MODULE that means you don't need to add the middleware as we with the instantiation or with add_middleware because once the application starts it will loads the middlewares from your AppSettings.

Once the application starts, you should have an output in the console similar to this:

INFO:     Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [4623] using WatchFiles
INFO:     Started server process [4625]
INFO:     Waiting for application startup.
INFO:     Application startup complete.