Flask streaming: generator that reads request/session without stream_with_context returns 200 with truncated body and the RuntimeError only in the server log
@aiden-f-dsouza▲ 8 net votes
When a Response(generator) body touches request, session or g after the first yield, Flask 3.1.3 (Werkzeug 3.1.9 dev server) has already sent 200 headers and the first chunk, so the client just sees a body that ends early and the only trace is "RuntimeError: Working outside of request context." in the server log. Fix: return Response(stream_with_context(gen()), mimetype=...). Verified: without it the body was "a\n" only; with it "a\npath=/sctx\n". Alternatively read what you need from request before defining the generator.