-
First check
Exampleimport asyncio
import logging
import time
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.background import BackgroundTasks
app = FastAPI()
@app.get("/")
async def read_root():
response_object = {"Hello": "World"}
tasks = BackgroundTasks()
tasks.add_task(bg_task)
return JSONResponse(response_object, 202, background=tasks)
async def bg_task():
logging.error("test1")
await asyncio.sleep(10)
logging.error("test2")
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
response.headers["X-Process-Time"] = str(time.time() - start_time)
response.headers["address"] = request.client.host
return response
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000,
log_level="debug", reload=True) Descriptionrun the above code, make a request to "/" but if you make only one request at a time this is fine, but if you make multiple request while background task is running problem #1 the second request start after first background task finishes Environment
Additional contextif i remove middleware code it works as expected |
Beta Was this translation helpful? Give feedback.
Replies: 11 comments 12 replies
-
I believe this is related to Starlette Issue 919: Background tasks don't work with middleware that subclasses |
Beta Was this translation helpful? Give feedback.
-
thank you @ycd seems like work is still in progress |
Beta Was this translation helpful? Give feedback.
-
@jkh911208 Could you close this issue, please? |
Beta Was this translation helpful? Give feedback.
-
For those who are searching for how to call background tasks under FastAPI middleware, here is quick solution: from starlette.background import BackgroundTask @app.middleware("http") You can add a time.sleep(10) in function A to see the result better. Hope this helps someone! |
Beta Was this translation helpful? Give feedback.
-
Hi @jkh911208 @Kludex , why is this issue |
Beta Was this translation helpful? Give feedback.
-
What is the version of your FastAPI? Oh sorry, yeah, this is still a thing. encode/starlette#1441 |
Beta Was this translation helpful? Give feedback.
-
I'm on v0.75.2 |
Beta Was this translation helpful? Give feedback.
-
Yes, don't use |
Beta Was this translation helpful? Give feedback.
-
In that case I couldn't add general before and after request actions, right? |
Beta Was this translation helpful? Give feedback.
-
No, I'm saying to not use that class. You can have middlewares: https://pgjones.dev/blog/how-to-write-asgi-middleware-2021 |
Beta Was this translation helpful? Give feedback.
-
This is solved on the latest FastAPI. |
Beta Was this translation helpful? Give feedback.
This is solved on the latest FastAPI.