Skip to content
Myr

refactor stream_with_context for async views (#5799)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by GitHub · parents 49b7e7b, 9822a03 · 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

3 files+62 added−31 removed

modified:src/flask/helpers.py+38 added-31 removed
11 unmodified lines
12from werkzeug.exceptions import abort as _wz_abort13from werkzeug.utils import redirect as _wz_redirect14from werkzeug.wrappers import Response as BaseResponse1516from .globals import _cv_app17from .globals import _cv_request18from .globals import current_app19from .globals import request20from .globals import request_ctx
41 unmodified lines
6263def 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.7071 This function however can help you keep the context around for longer::71 Use it as a decorator on a generator function:7273 .. code-block:: python7475 from flask import stream_with_context, request, Response7675 @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 "!"8485 return Response(generate())8684 Alternatively it can also be used around a specific generator::87 Or use it as a wrapper around a created generator:8889 .. code-block:: python9091 from flask import stream_with_context, request, Response9288 @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 "!"99100 return Response(stream_with_context(generate()))101102 .. versionadded:: 0.9103 """
6 unmodified lines
110 return stream_with_context(gen)111112 return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]113108 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 None120120 # 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]127128 # 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()137130 # 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_g144145146def make_response(*args: t.Any) -> Response:147 """Sometimes it is necessary to set additional headers in a view. Because
494 unmodified lines
modified:tests/test_helpers.py+23 added
304 unmodified lines
305306 rv = client.get("/")307 assert rv.data == b"flask"308309 def test_async_view(self, app, client):310 @app.route("/")311 async def index():312 flask.session["test"] = "flask"313314 @flask.stream_with_context315 def gen():316 yield flask.session["test"]317318 return flask.Response(gen())319320 # response is closed without reading stream321 client.get().close()322 # response stream is read323 assert client.get().text == "flask"324325 # same as above, but with client context preservation326 with client:327 client.get().close()328329 with client:330 assert client.get().text == "flask"331332333class TestHelpers:334 @pytest.mark.parametrize(335 ("debug", "expect"),336 [
47 unmodified lines
modified:CHANGES.rst+1 added
1 unmodified line
2-------------34Unreleased56- ``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