1010 API endpoints are built and served using the FastAPI micro-framework.
1111
1212"""
13+ from contextlib import asynccontextmanager
1314from . import __title__ , __version__
1415
1516from fastapi import FastAPI , Request , status , WebSocket
16- from fastapi .responses import JSONResponse
1717from fastapi .routing import APIRoute
1818
1919from .settings import settings
@@ -39,19 +39,33 @@ def generate_operation_id(route: APIRoute) -> str:
3939 return route .name
4040
4141
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+
4255"""A FastAPI application that serves handlers
4356"""
4457app = FastAPI (
4558 title = __title__ ,
4659 version = __version__ ,
47- description = settings .api_router .__doc__ ,
60+ description = str ( settings .api_router .__doc__ ) ,
4861 docs_url = settings .api_router .path_docs ,
4962 root_path = settings .api_router .path_root ,
5063 terms_of_service = settings .api_router .terms_of_service ,
5164 contact = settings .api_router .contact ,
5265 license_info = settings .api_router .license_info ,
5366 openapi_tags = settings .api_router .open_api_tags ,
5467 generate_unique_id_function = generate_operation_id ,
68+ lifespan = lifespan
5569)
5670
5771
@@ -67,23 +81,7 @@ async def websocket_endpoint(websocket: WebSocket):
6781app .include_router (router_root )
6882
6983
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-
8484# Default handler
85-
86-
8785@app .get (
8886 "/" ,
8987 status_code = status .HTTP_200_OK ,
@@ -93,5 +91,5 @@ async def root(request: Request) -> RootResponse:
9391 """
9492 return RootResponse (
9593 message = "Welcome to the {} API" .format (__name__ ),
96- root_path = request .scope .get ("root_path" )
94+ root_path = str ( request .scope .get ("root_path" ) )
9795 )
0 commit comments