Adding a middleware causes background tasks cancellation #6177
-
First Check
Commit to Help
Example Codeimport asyncio
import time
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
@app.middleware("http")
async def pass_all_middleware(request, call_next):
return await call_next(request)
async def test_bg():
try:
print("BG TASK STARTED")
await asyncio.sleep(5)
print("BG TASK ENDED")
except BaseException as be:
print("BG TASK NOT ENDED CORRECTLY", type(be))
@app.get("/hello")
async def root(background_tasks: BackgroundTasks):
background_tasks.add_task(test_bg)
return {"message": "hello"} DescriptionExecuting the sample code causes an unexpected (and apparently unrelated) asyncio Sample output running on uvicorn and calling GET on
The cause seems to be the introduction of a middleware; when removing the middleware fragment everything get fine:
Operating SystemmacOS Ventura Operating System DetailsDarwin ARM64 M1 FastAPI Version0.86.0 Python VersionPython 3.10.8 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
I believe this is an issue with See BaseHTTPMiddleware and this issue Possible solution: |
Beta Was this translation helpful? Give feedback.
-
Thank you. It seems that the issue has been fixed in starlette 0.21, so I'm looking forward to have the release with this #5471 |
Beta Was this translation helpful? Give feedback.
-
I think this can be closed after latest FastAPI release. Thank you |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help here @odiseo0 ! 👏 🙇 Thanks for reporting back and closing the issue @csuriano23 👍 |
Beta Was this translation helpful? Give feedback.
Thank you. It seems that the issue has been fixed in starlette 0.21, so I'm looking forward to have the release with this #5471