{"id":"4c4104fd5a665ce2","repo":"pallets/flask","slug":"stream-with-context-can-only-be-used-when-a-requ","errorCode":null,"errorMessage":"'stream_with_context' can only be used when a request context is active, such as in a view function.","messagePattern":"'stream_with_context' can only be used when a request context is active, such as in a view function\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/flask/helpers.py","lineNumber":128,"sourceCode":"                yield \"!\"\n\n            return Response(stream_with_context(generate()))\n\n    .. versionadded:: 0.9\n    \"\"\"\n    try:\n        gen = iter(generator_or_function)  # type: ignore[arg-type]\n    except TypeError:\n\n        def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:\n            gen = generator_or_function(*args, **kwargs)  # type: ignore[operator]\n            return stream_with_context(gen)\n\n        return update_wrapper(decorator, generator_or_function)  # type: ignore[arg-type]\n\n    def generator() -> t.Iterator[t.AnyStr]:\n        if (ctx := _cv_app.get(None)) is None:\n            raise RuntimeError(\n                \"'stream_with_context' can only be used when a request\"\n                \" context is active, such as in a view function.\"\n            )\n\n        with ctx:\n            yield None  # type: ignore[misc]\n\n            try:\n                yield from gen\n            finally:\n                # Clean up in case the user wrapped a WSGI iterator.\n                if hasattr(gen, \"close\"):\n                    gen.close()\n\n    # Execute the generator to the sentinel value. This captures the current\n    # context and pushes it to preserve it. Further iteration will yield from\n    # the original iterator.\n    wrapped_g = generator()","sourceCodeStart":110,"sourceCodeEnd":146,"githubUrl":"https://github.com/pallets/flask/blob/6a2f545bfd8ed31e19066a299296917e034aca58/src/flask/helpers.py#L110-L146","documentation":"stream_with_context keeps the current request context alive while a streaming response generator runs. It captures the active context from the _cv_app context variable at first iteration; if no request context is active there is nothing to preserve, so the wrapped generator raises RuntimeError when consumed.","triggerScenarios":"Iterating a stream_with_context(...) generator outside a request — e.g. constructing it in a background thread, a CLI command, app startup code, or a test without test_request_context(); also wrapping a generator in a view but consuming it after the context was torn down without Flask's Response driving it.","commonSituations":"Moving streaming code into Celery/thread workers; unit tests calling the view function directly instead of via test_client; calling next() on the generator eagerly before returning the Response.","solutions":["Only create and return stream_with_context generators from inside a view function, wrapped in Response(stream_with_context(gen())).","In tests, wrap consumption in app.test_request_context(): with app.test_request_context('/'): ...","If no request data is actually needed, drop stream_with_context and pass the plain generator to Response.","For background work, copy the needed request values into local variables before spawning the worker instead of streaming the context."],"exampleFix":"# before\ngen = stream_with_context(generate())\nnext(gen)  # outside any request\n# after\n@app.route('/stream')\ndef stream():\n    return Response(stream_with_context(generate()))","handlingStrategy":"type-guard","validationCode":"from flask import has_request_context\nif not has_request_context():\n    raise RuntimeError(\"stream_with_context must be called inside a view/request; restructure the code\")","typeGuard":"from flask import has_request_context\ndef can_stream_with_context() -> bool:\n    return has_request_context()","tryCatchPattern":"try:\n    return Response(stream_with_context(generate()))\nexcept RuntimeError:\n    # called outside a request (e.g. CLI/背景 job) — capture needed values eagerly instead\n    raise","preventionTips":["Call stream_with_context only inside view functions, not at import time or in background tasks","In tests, wrap calls in app.test_request_context()","If a generator needs request data outside a request, copy the values into locals before spawning the worker"],"tags":["flask","request-context","streaming"],"analyzedSha":"6a2f545bfd8ed31e19066a299296917e034aca58","analyzedAt":"2026-07-31T19:13:49.921Z","schemaVersion":2}