First Check
Commit to Help
Example Code
import 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"}
Description
Executing the sample code causes an unexpected (and apparently unrelated) asyncio CancelledError on long running background tasks.
Sample output running on uvicorn and calling GET on /hello endpoint:
INFO: Started server process [95599]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:57617 - "GET /hello HTTP/1.1" 200 OK
BG TASK STARTED
BG TASK NOT ENDED CORRECTLY <class 'asyncio.exceptions.CancelledError'>
The cause seems to be the introduction of a middleware; when removing the middleware fragment everything get fine:
INFO: Started server process [96777]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:57674 - "GET /hello HTTP/1.1" 200 OK
BG TASK STARTED
BG TASK ENDED
Operating System
macOS Ventura
Operating System Details
Darwin ARM64 M1
FastAPI Version
0.86.0
Python Version
Python 3.10.8
Additional Context
No response
First Check
Commit to Help
Example Code
Description
Executing the sample code causes an unexpected (and apparently unrelated) asyncio
CancelledErroron long running background tasks.Sample output running on uvicorn and calling GET on
/helloendpoint:The cause seems to be the introduction of a middleware; when removing the middleware fragment everything get fine:
Operating System
macOS Ventura
Operating System Details
Darwin ARM64 M1
FastAPI Version
0.86.0
Python Version
Python 3.10.8
Additional Context
No response