Hello there,
Description
I have a middleware in my application, but, it is gigantic, and I want to move it to a different file. I would like to know if it is possible to access @app
in a file that is not my main.py
.
My main.py
looks something like this:
import uvicorn
from fastapi import Depends, FastAPI, Header, HTTPException
from routers.supply_change import predict
app = FastAPI(title=title, description=description,
version=version, docs_url=docs_url, redoc_url=redoc_url)
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
# Do some stuff
response = await call_next(request)
# Do some stuff
return response
app.include_router(predict.router)
but I want something like this:
main.py
import uvicorn
from fastapi import Depends, FastAPI, Header, HTTPException
from routers.supply_change import predict
app = FastAPI(title=title, description=description,
version=version, docs_url=docs_url, redoc_url=redoc_url)
app.include_router(predict.router)
middleware.py
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
# Do some stuff
response = await call_next(request)
# Do some stuff
return response
You usually want to do it the other way around: Define a middleware function or class in a separate file, and then import that in your main where it will be attached to your app.
The decorator syntax for middlewares is equivalent to app.add_middleware(BaseHTTPMiddleware, dispatch=add_process_time_header)
, so what you should be doing is:
import uvicorn
from fastapi import Depends, FastAPI, Header, HTTPException
from routers.supply_change import predict
from starlette.middleware import BaseHTTPMiddleware
from .middleware import add_process_time_header
app = FastAPI(title=title, description=description,
version=version, docs_url=docs_url, redoc_url=redoc_url)
app.add_middleware(BaseHTTPMiddleware, dispatch=add_process_time_header)
app.include_router(predict.router)
I did what you said, and it looks sooooo clean, thanks!
Thanks for the help here @sm-Fifteen ! :clap: :bow:
Thanks for reporting back and closing the issue @RenanAlonkin :+1:
Most helpful comment
You usually want to do it the other way around: Define a middleware function or class in a separate file, and then import that in your main where it will be attached to your app.
The decorator syntax for middlewares is equivalent to
app.add_middleware(BaseHTTPMiddleware, dispatch=add_process_time_header)
, so what you should be doing is: