Why middleware waits for all scheduled tasks to finish?
See original GitHub issueDescription
I schedule tasks to event loop like this:
async def wait_to_finish():
time.sleep(5)
print('finished')
@router.get("/async/background")
async def get() -> bool:
asyncio.create_task(wait_to_finish())
return True
And it works well. True
returned as response without waiting wait_to_finish()
function to finish. And wait_to_finish()
function runs in the event loop and prints “finished”. Everything works well until here.
But when I add a middleware like this:
async def catch_exceptions_middleware(request: Request, call_next):
try:
return await call_next(request)
except Exception as exc:
logger.exception("Exception")
return JSONResponse(status_code=getattr(exc, "status_code", 500),
content={"message": f"Unexpected error occured."})
app.middleware('http')(catch_exceptions_middleware)
It waits to finish all tasks I created in the event loop before sending response. Thus it takes 5+ secs. to send response, in this example. Why middlewares force the event loop to finish all the tasks? How can I avoid this ? (Without using background-tasks. There are many reason I don’t use it. And remember, this works pretty well until I add a middleware as shown above).
Environment
- OS: macOS
- FastAPI Version : 0.61.0
- Python version: 3.8.5
Issue Analytics
- State:
- Created 3 years ago
- Comments:18 (14 by maintainers)
Top Results From Across the Web
using @Scheduled and @Async together? - Stack Overflow
ScheduledThreadPoolExecutor waits until Runnable#run() is finished and sets the next execution time using the start time and the fixed rate.
Read more >2 Managing Scheduled Tasks - Oracle Help Center
This scheduled task gets back the result of SoD Evaluation from the SoD Server, for example, OAACG, SAP, and GRC for all requests...
Read more >Scheduled tasks with Hyperlambda and retry - Aista
First of all it's using a semaphore to make sure maximum 8 tasks are executed simultaneously. If task number 9 tries to execute,...
Read more >Middleware Support for Aperiodic Tasks in ... - CiteSeerX
To fairly compare with the alternative approach (AUB), all periodic tasks and the server itself are scheduled by a preemptive end-to-end deadline monotonic....
Read more >Background tasks with hosted services in ASP.NET Core
However, tasks aren't abandoned after cancellation is requested—the caller awaits all tasks to complete. If the app shuts down unexpectedly ...
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
That’s pretty disappointing… Thank you @ycd
@Kludex doesn’t using a Middleware that inherits BaseHTTPMiddleware brokes the BackgroundTasks?
See Starlette Issues 919