I have a /users route in my app which is initialized with a default router like this :
(Note that responses and dependencies have been removed from the snippet to protect proprietary code)
api_router = APIRouter(
responses={},
route_class=LocalizationRoute,
dependencies=[],
)
Localization Route is being used directly from fastapi-localizationpackage for translation purpose.
Now I want to add another router to the same route for the purpose of logging . This router is based on the following router class
def log_info(req_body, res_body):
print(req_body)
print(res_body)
class LoggingRoute(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()
async def custom_route_handler(request: Request) -> Response:
req_body = await request.body()
response = await original_route_handler(request)
if isinstance(response, StreamingResponse):
res_body = b''
async for item in response.body_iterator:
res_body += item
task = BackgroundTask(log_info, req_body, res_body)
return Response(content=res_body, status_code=response.status_code,
headers=dict(response.headers), media_type=response.media_type, background=task)
else:
res_body = response.body
response.background = BackgroundTask(log_info, req_body, res_body)
return response
return custom_route_handler
I tried doing this by using include
router
clause like this :
api_
router.include_
router(APIRouter(router
_class= LoggingRoute))
But this is not working. I can see the router class is still set to Localization Route and the routerclass argument in include_
router
statement is ignored.
So I was wondering do fast api not support adding multiple routers with different router class to the same route ?