Debian Codegraph @

docs/examples/dependency_injection/dependency_yield_exceptions.py

raw
1 from typing import Dict, Generator
2
3 from litestar import Litestar, get
4 from litestar.di import Provide
5
6 STATE = {"result": None, "connection": "closed"}
7
8
9 def generator_function() -> Generator[str, None, None]:
10 """Set the connection state to open and close it after the handler returns.
11
12 If an error occurs, set `result` to `"error"`, else set it to `"OK"`.
13 """
14 try:
15 STATE["connection"] = "open"
16 yield "hello"
17 STATE["result"] = "OK"
18 except ValueError:
19 STATE["result"] = "error"
20 finally:
21 STATE["connection"] = "closed"
22
23
24 @get("/{name:str}", dependencies={"message": Provide(generator_function)})
25 def index(name: str, message: str) -> Dict[str, str]:
26 """If `name` is "John", return a message, otherwise raise an error."""
27 if name == "John":
28 return {name: message}
29 raise ValueError()
30
31
32 app = Litestar(route_handlers=[index])