Debian Codegraph @

docs/examples/application_hooks/before_send_hook.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING
4
5 from litestar import Litestar, get
6 from litestar.datastructures import MutableScopeHeaders
7
8 if TYPE_CHECKING:
9 from typing import Dict
10
11 from litestar.types import Message, Scope
12
13
14 @get("/test", sync_to_thread=False)
15 def handler() -> Dict[str, str]:
16 """Example Handler function."""
17 return {"key": "value"}
18
19
20 async def before_send_hook_handler(message: Message, scope: Scope) -> None:
21 """The function will be called on each ASGI message.
22
23 We therefore ensure it runs only on the message start event.
24 """
25 if message["type"] == "http.response.start":
26 headers = MutableScopeHeaders.from_message(message=message)
27 headers["My-Header"] = Litestar.from_scope(scope).state.message
28
29
30 def on_startup(app: Litestar) -> None:
31 """A function that will populate the app state before any requests are received."""
32 app.state.message = "value injected during send"
33
34
35 app = Litestar(route_handlers=[handler], on_startup=[on_startup], before_send=[before_send_hook_handler])