BackgroundTasks can't work with middleware
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
import asyncio
from fastapi import Request, BackgroundTasks, FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
async def test_sleep():
print('test')
await asyncio.sleep(9999)
@app.post("/test")
async def test(background_tasks: BackgroundTasks):
background_tasks.add_task(test_sleep)
return 'test'
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
response = await call_next(request)
return response
Description
When use middleware, the second request to ‘http://127.0.0.1:8000/test’ will be pending. If I remove middleware, everything works fine. I know it’s the middleware problem, but I don’t known how to fix it.
Operating System
Linux
Operating System Details
Ubuntu 20.04
FastAPI Version
0.66.1
Python Version
3.9.5
Additional Context
No response
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:8
Top Results From Across the Web
FastAPI Background task in middleware - Stack Overflow
I'm trying to add background tasks to ...
Read more >Solve the drawbacks with FastAPI BackgroundTasks - Johachi
Drawbacks of FastAPI's BackgroundTask and how to solve them.
Read more >CORS (Cross-Origin Resource Sharing) - FastAPI
Import CORSMiddleware . Create a list of allowed origins (as strings). Add it as a "middleware" to your FastAPI application. You can also ......
Read more >Why you don't need RPA, but Middleware as a Service is the ...
Because not every application used is compatible with the others. Middleware then acts as a translator to mediate between the applications or two...
Read more >The Background on Background Tasks in .NET 6 - YouTube
There are lots of scenarios for background tasks ranging from a task that ... as well as a deep dive on how these...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This is a known starlette issue https://github.com/encode/starlette/issues/919
I’m seeing a probably related issue but with different symptoms than skk294 or the ones described in the starlette issue. Here is my code:
Python 3.10.4, Fastapi 0.78.0, Uvicorn 0.17.6
The symptom is that the background task hangs as soon as it encounters
await asyncio.sleep
. Future requests will go the same way: I see “finishing middleware”, and “starting background task”, but never “finished background task”. If I remove the middleware, it works.Interestingly this only happens with asyncio: if I replace asyncio.sleep with time.sleep (and remove the await), it works even with the middleware.