How to add middleware in different places? #10142
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, Request, Depends
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
from fastapi import Request, Response
import time
from main import app
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return responseDescriptionI've noticed that middleware functions in FastAPI need to be in the same .py file as the code containing app = FastAPI() in order for the middleware function to work. in main.py: from fastapi import FastAPI, Request, Depends
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)This cross-origin middleware is effective. However, I created a directory named "middleware" at the same level as the main.py, and inside that directory, there's a file named "demo_middleware.py". in demo_middleware.py from fastapi import Request, Response
import time
from main import app
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return responseHowever, this middleware function for measuring time isn't functioning. Operating SystemWindows Operating System DetailsNo response FastAPI Version0.100.0 Pydantic Version1.10.7 Python VersionPython 3.8.16 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
you can manually like you mentioned for CORS some like you can follow #397 to get more idea |
Beta Was this translation helpful? Give feedback.
-
|
Remove or Another way is to convert your middleware into the pure ASGI middleware and add it using |
Beta Was this translation helpful? Give feedback.
Remove
from main import appand@app.middleware("http")fromdemo_middlewaremodule, then import your middleware to themainmodule and add middleware to the stack usingor
Another way is to convert your middleware into the pure ASGI middleware and add it using
app.add_middleware(YourMiddlewareClass)