@@ -35,10 +35,22 @@ from starlette.applications import Starlette
35
35
from starlette.middleware import Middleware
36
36
from starlette.requests import Request
37
37
from starlette.responses import JSONResponse
38
+ from starlette.routing import Route
38
39
39
40
from starlette_context import context, plugins
40
41
from starlette_context.middleware import ContextMiddleware
41
42
43
+ async def index (request : Request):
44
+ # Access and store data in context
45
+ context[" custom_value" ] = " example"
46
+ return JSONResponse(context.data)
47
+
48
+ # Define routes
49
+ routes = [
50
+ Route(" /" , endpoint = index)
51
+ ]
52
+
53
+ # Configure middleware
42
54
middleware = [
43
55
Middleware(
44
56
ContextMiddleware,
@@ -49,13 +61,11 @@ middleware = [
49
61
)
50
62
]
51
63
52
- app = Starlette(middleware = middleware)
53
-
54
-
55
- @app.route (" /" )
56
- async def index (request : Request):
57
- return JSONResponse(context.data)
58
-
64
+ # Create application with routes and middleware
65
+ app = Starlette(
66
+ routes = routes,
67
+ middleware = middleware
68
+ )
59
69
60
70
if __name__ == " __main__" :
61
71
uvicorn.run(app, host = " 0.0.0.0" )
@@ -66,7 +76,8 @@ In this example the response contains a JSON with:
66
76
``` json
67
77
{
68
78
"X-Correlation-ID" : " 5ca2f0b43115461bad07ccae5976a990" ,
69
- "X-Request-ID" : " 21f8d52208ec44948d152dc49a713fdd"
79
+ "X-Request-ID" : " 21f8d52208ec44948d152dc49a713fdd" ,
80
+ "custom_value" : " example"
70
81
}
71
82
```
72
83
0 commit comments