-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Closed
Labels
Description
First check
- [x ] I added a very descriptive title to this issue.
- [ x] I used the GitHub search to find a similar issue and didn't find it.
- [ x] I searched the FastAPI documentation, with the integrated search.
- [ x] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [ x] I already read and followed all the tutorial in the docs and didn't find an answer.
- [ x] I already checked if it is not related to FastAPI but to Pydantic.
- [ x] I already checked if it is not related to FastAPI but to Swagger UI.
- [ x] I already checked if it is not related to FastAPI but to ReDoc.
- [ x] After submitting this, I commit to one of:
- Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
- I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
- Implement a Pull Request for a confirmed bug.
Example
import 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)Description
run the above code, make a request to "/"
you will see

which logging is happening before return the object
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
problem #2 when background task of second request finishes, it throw error

Environment
- OS: [e.g. Linux / Windows / macOS]: macos and debian
- FastAPI Version [e.g. 0.3.0]: 0.61.1
- Python version: 3.8.5
Additional context
if i remove middleware code it works as expected

all requests are handled and all background tasks are working fine no exception