refactor stream_with_context for async views
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 49b7e7b · Browse files · 3 files·+62 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+62 added−31 removed
- tests:+23 added−0 removed
- other:+39 added−31 removed
Provenance
- Commit
9822a03- Tree
b126aa3- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
49b7e7b
3 files changed+62 added−31 removed
modified:src/flask/helpers.py+38 added-31 removed
11 unmodified lines12 from werkzeug.exceptions import abort as _wz_abort13 from werkzeug.utils import redirect as _wz_redirect14 from werkzeug.wrappers import Response as BaseResponse15 16+from .globals import _cv_app17 from .globals import _cv_request18 from .globals import current_app19 from .globals import request20 from .globals import request_ctx41 unmodified lines62 63 def stream_with_context(64 generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]],65 ) -> t.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]:65- """Request contexts disappear when the response is started on the server.66- This is done for efficiency reasons and to make it less likely to encounter67- memory leaks with badly written WSGI middlewares. The downside is that if68- you are using streamed responses, the generator cannot access request bound69- information any more.66+ """Wrap a response generator function so that it runs inside the current67+ request context. This keeps :data:`request`, :data:`session`, and :data:`g`68+ available, even though at the point the generator runs the request context69+ will typically have ended.70 71- This function however can help you keep the context around for longer::71+ Use it as a decorator on a generator function:72 73+ .. code-block:: python74+75 from flask import stream_with_context, request, Response76 75- @app.route('/stream')77+ @app.get("/stream")78 def streamed_response():79 @stream_with_context80 def generate():79- yield 'Hello '80- yield request.args['name']81- yield '!'81+ yield "Hello "82+ yield request.args["name"]83+ yield "!"84+85 return Response(generate())86 84- Alternatively it can also be used around a specific generator::87+ Or use it as a wrapper around a created generator:88 89+ .. code-block:: python90+91 from flask import stream_with_context, request, Response92 88- @app.route('/stream')93+ @app.get("/stream")94 def streamed_response():95 def generate():91- yield 'Hello '92- yield request.args['name']93- yield '!'96+ yield "Hello "97+ yield request.args["name"]98+ yield "!"99+100 return Response(stream_with_context(generate()))101 102 .. versionadded:: 0.9103 """6 unmodified lines110 return stream_with_context(gen)111 112 return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]113 108- def generator() -> t.Iterator[t.AnyStr | None]:109- ctx = _cv_request.get(None)110- if ctx is None:114+ def generator() -> t.Iterator[t.AnyStr]:115+ if (req_ctx := _cv_request.get(None)) is None:116 raise RuntimeError(117 "'stream_with_context' can only be used when a request"118 " context is active, such as in a view function."119 )115- with ctx:116- # Dummy sentinel. Has to be inside the context block or we're117- # not actually keeping the context around.118- yield None120 120- # The try/finally is here so that if someone passes a WSGI level121- # iterator in we're still running the cleanup logic. Generators122- # don't need that because they are closed on their destruction123- # automatically.121+ app_ctx = _cv_app.get()122+ # Setup code below will run the generator to this point, so that the123+ # current contexts are recorded. The contexts must be pushed after,124+ # otherwise their ContextVar will record the wrong event loop during125+ # async view functions.126+ yield None # type: ignore[misc]127+128+ # Push the app context first, so that the request context does not129+ # automatically create and push a different app context.130+ with app_ctx, req_ctx:131 try:132 yield from gen133 finally:134+ # Clean up in case the user wrapped a WSGI iterator.135 if hasattr(gen, "close"):136 gen.close()137 130- # The trick is to start the generator. Then the code execution runs until131- # the first dummy None is yielded at which point the context was already132- # pushed. This item is discarded. Then when the iteration continues the133- # real generator is executed.138+ # Execute the generator to the sentinel value. This ensures the context is139+ # preserved in the generator's state. Further iteration will push the140+ # context and yield from the original iterator.141 wrapped_g = generator()142 next(wrapped_g)136- return wrapped_g # type: ignore[return-value]143+ return wrapped_g144 145 146 def make_response(*args: t.Any) -> Response:147 """Sometimes it is necessary to set additional headers in a view. Because494 unmodified linesmodified:tests/test_helpers.py+23 added
304 unmodified lines305 306 rv = client.get("/")307 assert rv.data == b"flask"308 309+ def test_async_view(self, app, client):310+ @app.route("/")311+ async def index():312+ flask.session["test"] = "flask"313 314+ @flask.stream_with_context315+ def gen():316+ yield flask.session["test"]317+318+ return flask.Response(gen())319+320+ # response is closed without reading stream321+ client.get().close()322+ # response stream is read323+ assert client.get().text == "flask"324+325+ # same as above, but with client context preservation326+ with client:327+ client.get().close()328+329+ with client:330+ assert client.get().text == "flask"331+332+333 class TestHelpers:334 @pytest.mark.parametrize(335 ("debug", "expect"),336 [47 unmodified linesmodified:CHANGES.rst+1 added
1 unmodified line2 -------------3 4 Unreleased5 6+- ``stream_with_context`` does not fail inside async views. :issue:`5774`7 - When using ``follow_redirects`` in the test client, the final state8 of ``session`` is correct. :issue:`5786`9 - Relax type hint for passing bytes IO to ``send_file``. :issue:`5776`10 1614 unmodified lines