Debian Codegraph @

docs/examples/datastructures/headers/etag.py

raw
1 import random
2 import time
3
4 from litestar import Controller, Litestar, get
5 from litestar.datastructures import ETag
6 from litestar.enums import MediaType
7 from litestar.response import Response
8
9
10 class MyController(Controller):
11 etag = ETag(value="foo")
12
13 @get("/chance_of_rain")
14 def get_chance_of_rain(self) -> float:
15 """This endpoint uses the etag value in the controller which overrides the app value.
16
17 The returned header will be `etag: "foo"`
18 """
19 return 0.5
20
21 @get("/timestamp", etag=ETag(value="bar"))
22 def get_server_time(self) -> float:
23 """This endpoint overrides the etag defined in the controller.
24
25 The returned header will be `etag: W/"bar"`
26 """
27 return time.time()
28
29
30 @get("/population")
31 def get_population_count() -> int:
32 """This endpoint will use the etag defined in the app.
33
34 The returned header will be `etag: "bar"`
35 """
36 return 100000
37
38
39 @get("/population-dynamic", etag=ETag(documentation_only=True))
40 def get_population_count_dynamic() -> Response[str]:
41 """The etag defined in this route handler will not be returned, and does not need a value.
42
43 It will only be used for OpenAPI generation.
44 """
45 population_count = random.randint(0, 1000)
46 return Response(
47 content=str(population_count),
48 headers={"etag": str(population_count)},
49 media_type=MediaType.TEXT,
50 status_code=200,
51 )
52
53
54 app = Litestar(route_handlers=[MyController, get_population_count], etag=ETag(value="bar"))