Skip to content

middleware breaks behavior of background task #2215

@jkh911208

Description

@jkh911208

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
Screen Shot 2020-10-21 at 8 50 42 AM
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
Screen Shot 2020-10-21 at 8 52 39 AM

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
Screen Shot 2020-10-21 at 8 55 24 AM
all requests are handled and all background tasks are working fine no exception

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions