10
10
API endpoints are built and served using the FastAPI micro-framework.
11
11
12
12
"""
13
+ from contextlib import asynccontextmanager
13
14
from . import __title__ , __version__
14
15
15
16
from fastapi import FastAPI , Request , status , WebSocket
16
- from fastapi .responses import JSONResponse
17
17
from fastapi .routing import APIRoute
18
18
19
19
from .settings import settings
@@ -39,19 +39,33 @@ def generate_operation_id(route: APIRoute) -> str:
39
39
return route .name
40
40
41
41
42
+ @asynccontextmanager
43
+ async def lifespan (_fastapi : FastAPI ):
44
+ if broker .is_worker_process :
45
+ # TaskIQ configurartion so we can share FastAPI dependencies in tasks
46
+ await broker .startup ()
47
+
48
+ yield
49
+
50
+ if broker .is_worker_process :
51
+ # On shutdown, we need to shutdown the broker
52
+ await broker .shutdown ()
53
+
54
+
42
55
"""A FastAPI application that serves handlers
43
56
"""
44
57
app = FastAPI (
45
58
title = __title__ ,
46
59
version = __version__ ,
47
- description = settings .api_router .__doc__ ,
60
+ description = str ( settings .api_router .__doc__ ) ,
48
61
docs_url = settings .api_router .path_docs ,
49
62
root_path = settings .api_router .path_root ,
50
63
terms_of_service = settings .api_router .terms_of_service ,
51
64
contact = settings .api_router .contact ,
52
65
license_info = settings .api_router .license_info ,
53
66
openapi_tags = settings .api_router .open_api_tags ,
54
67
generate_unique_id_function = generate_operation_id ,
68
+ lifespan = lifespan
55
69
)
56
70
57
71
@@ -67,23 +81,7 @@ async def websocket_endpoint(websocket: WebSocket):
67
81
app .include_router (router_root )
68
82
69
83
70
- # TaskIQ configurartion so we can share FastAPI dependencies in tasks
71
- @app .on_event ("startup" )
72
- async def app_startup ():
73
- if not broker .is_worker_process :
74
- await broker .startup ()
75
-
76
- # On shutdown, we need to shutdown the broker
77
-
78
-
79
- @app .on_event ("shutdown" )
80
- async def app_shutdown ():
81
- if not broker .is_worker_process :
82
- await broker .shutdown ()
83
-
84
84
# Default handler
85
-
86
-
87
85
@app .get (
88
86
"/" ,
89
87
status_code = status .HTTP_200_OK ,
@@ -93,5 +91,5 @@ async def root(request: Request) -> RootResponse:
93
91
"""
94
92
return RootResponse (
95
93
message = "Welcome to the {} API" .format (__name__ ),
96
- root_path = request .scope .get ("root_path" )
94
+ root_path = str ( request .scope .get ("root_path" ) )
97
95
)
0 commit comments