| 1 |
from os import urandom |
| 2 |
from typing import Dict |
| 3 |
|
| 4 |
from litestar import Litestar, Request, delete, get, post |
| 5 |
from litestar.middleware.session.client_side import CookieBackendConfig |
| 6 |
|
| 7 |
# we initialize to config with a 16 byte key, i.e. 128 a bit key. |
| 8 |
# in real world usage we should inject the secret from the environment |
| 9 |
session_config = CookieBackendConfig(secret=urandom(16)) # type: ignore[arg-type] |
| 10 |
|
| 11 |
|
| 12 |
@get("/session", sync_to_thread=False) |
| 13 |
def check_session_handler(request: Request) -> Dict[str, bool]: |
| 14 |
"""Handler function that accesses request.session.""" |
| 15 |
return {"has_session": request.session != {}} |
| 16 |
|
| 17 |
|
| 18 |
@post("/session", sync_to_thread=False) |
| 19 |
def create_session_handler(request: Request) -> None: |
| 20 |
"""Handler to set the session.""" |
| 21 |
if not request.session: |
| 22 |
# value can be a dictionary or pydantic model |
| 23 |
request.set_session({"username": "moishezuchmir"}) |
| 24 |
|
| 25 |
|
| 26 |
@delete("/session", sync_to_thread=False) |
| 27 |
def delete_session_handler(request: Request) -> None: |
| 28 |
"""Handler to clear the session.""" |
| 29 |
if request.session: |
| 30 |
request.clear_session() |
| 31 |
|
| 32 |
|
| 33 |
app = Litestar( |
| 34 |
route_handlers=[check_session_handler, create_session_handler, delete_session_handler], |
| 35 |
middleware=[session_config.middleware], |
| 36 |
) |