| 1 |
import logging |
| 2 |
from typing import TYPE_CHECKING, Any |
| 3 |
|
| 4 |
from litestar import Litestar, Request, get |
| 5 |
from litestar.datastructures import State |
| 6 |
from litestar.di import NamedDependency, Provide |
| 7 |
|
| 8 |
if TYPE_CHECKING: |
| 9 |
from litestar.types import ASGIApp, Receive, Scope, Send |
| 10 |
|
| 11 |
logger = logging.getLogger(__name__) |
| 12 |
|
| 13 |
|
| 14 |
def set_state_on_startup(app: Litestar) -> None: |
| 15 |
"""Startup and shutdown hooks can receive `State` as a keyword arg.""" |
| 16 |
app.state.value = "abc123" |
| 17 |
|
| 18 |
|
| 19 |
def middleware_factory(*, app: "ASGIApp") -> "ASGIApp": |
| 20 |
"""A middleware can access application state via `scope`.""" |
| 21 |
|
| 22 |
async def my_middleware(scope: "Scope", receive: "Receive", send: "Send") -> None: |
| 23 |
state = Litestar.from_scope(scope).state |
| 24 |
logger.info("state value in middleware: %s", state.value) |
| 25 |
await app(scope, receive, send) |
| 26 |
|
| 27 |
return my_middleware |
| 28 |
|
| 29 |
|
| 30 |
async def my_dependency(state: State) -> Any: |
| 31 |
"""Dependencies can receive state via injection.""" |
| 32 |
logger.info("state value in dependency: %s", state.value) |
| 33 |
|
| 34 |
|
| 35 |
@get("/", dependencies={"dep": Provide(my_dependency)}, middleware=[middleware_factory], sync_to_thread=False) |
| 36 |
def get_handler(state: State, request: Request, dep: NamedDependency[Any]) -> None: |
| 37 |
"""Handlers can receive state via injection.""" |
| 38 |
logger.info("state value in handler from `State`: %s", state.value) |
| 39 |
logger.info("state value in handler from `Request`: %s", request.app.state.value) |
| 40 |
|
| 41 |
|
| 42 |
app = Litestar(route_handlers=[get_handler], on_startup=[set_state_on_startup]) |