Can a Flask view detect that the client disconnected and stop long-running work early?
0 reputation · 23 Apr 2020, 12:54 UTC
I have a Flask application with a few synchronous view functions that run expensive operations — report generation and large data exports that can take 30–60 seconds. If a user closes the browser tab or cancels the request halfway through, I would like the view to stop working and release its resources instead of running to completion for a response nobody will receive.
My understanding is that Flask itself provides no request-level cancellation signal, and that under a WSGI server like Gunicorn the worker thread keeps executing the view even after the client disconnects. I have seen references to request.is_disconnected and to asyncio.CancelledError in async views, but it is unclear which of these are portable across servers and which depend on specific ASGI behavior like the http.disconnect event.
Assume Flask 2.x/3.x deployed behind Gunicorn (sync workers), with the option to move to an ASGI server such as Hypercorn if that changes the answer.
Is there any documented, server-independent way for a Flask view to detect a client disconnect mid-request and abort work? If not, does converting the view to async def under an ASGI server reliably deliver cancellation, and are there caveats with blocking calls inside it? Finally, is polling request.is_disconnected between chunks of work a supported pattern, or is it server-specific?