Skip to content
Myr

Added flask.stream_with_context

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

authored by Armin Ronacher · committed by Armin Ronacher · parent 2e816f5 · Browse files · 8 files+222 added−27 removed
This commit

State

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

Diff stats

8 files+222 added−27 removed

  • other:+222 added−27 removed

8 files+222 added−27 removed

modified:docs/patterns/streaming.rst+23 added
57 unmodified lines
58The template is then evaluated as the stream is iterated over. Since each59time you do a yield the server will flush the content to the client you60might want to buffer up a few items in the template which you can do with61``rv.enable_buffering(size)``. ``5`` is a sane default.6263Streaming with Context64----------------------6566.. versionadded:: 0.96768Note that when you stream data, the request context is already gone the69moment the function executes. Flask 0.9 provides you with a helper that70can keep the request context around during the execution of the71generator::7273 from flask import stream_with_context, request, Response7475 @app.route('/stream')76 def streamed_response():77 def generate():78 yield 'Hello '79 yield request.args['name']80 yield '!'81 return Response(stream_with_context(generate()))8283Without the :func:`~flask.stream_with_context` function you would get a84:class:`RuntimeError` at that point.
modified:docs/api.rst+5 added
373 unmodified lines
374 from flask.ext import foo375376 .. versionadded:: 0.8377378Stream Helpers379--------------380381.. autofunction:: stream_with_context382383Useful Internals384----------------385386.. autoclass:: flask.ctx.RequestContext
277 unmodified lines
modified:flask/testsuite/appctx.py+20 added
73 unmodified lines
74 with app.test_request_context():75 self.assert_equal(76 flask.render_template_string('{{ g.spam }}'), 'eggs')7778 def test_context_refcounts(self):79 called = []80 app = flask.Flask(__name__)81 @app.teardown_request82 def teardown_req(error=None):83 called.append('request')84 @app.teardown_appcontext85 def teardown_app(error=None):86 called.append('app')87 @app.route('/')88 def index():89 with flask._app_ctx_stack.top:90 with flask._request_ctx_stack.top:91 pass92 self.assert_(flask._request_ctx_stack.request.environ93 ['werkzeug.request'] is not None)94 c = app.test_client()95 c.get('/')96 self.assertEqual(called, ['request', 'app'])979899def suite():100 suite = unittest.TestSuite()101 suite.addTest(unittest.makeSuite(AppContextTestCase))102 return suite
modified:flask/testsuite/helpers.py+59 added
395 unmodified lines
396 except NotImplementedError:397 self.fail('Flask(import_name) is importing import_name.')398399400class StreamingTestCase(FlaskTestCase):401402 def test_streaming_with_context(self):403 app = flask.Flask(__name__)404 app.testing = True405 @app.route('/')406 def index():407 def generate():408 yield 'Hello '409 yield flask.request.args['name']410 yield '!'411 return flask.Response(flask.stream_with_context(generate()))412 c = app.test_client()413 rv = c.get('/?name=World')414 self.assertEqual(rv.data, 'Hello World!')415416 def test_streaming_with_context_as_decorator(self):417 app = flask.Flask(__name__)418 app.testing = True419 @app.route('/')420 def index():421 @flask.stream_with_context422 def generate():423 yield 'Hello '424 yield flask.request.args['name']425 yield '!'426 return flask.Response(generate())427 c = app.test_client()428 rv = c.get('/?name=World')429 self.assertEqual(rv.data, 'Hello World!')430431 def test_streaming_with_context_and_custom_close(self):432 app = flask.Flask(__name__)433 app.testing = True434 called = []435 class Wrapper(object):436 def __init__(self, gen):437 self._gen = gen438 def __iter__(self):439 return self440 def close(self):441 called.append(42)442 def next(self):443 return self._gen.next()444 @app.route('/')445 def index():446 def generate():447 yield 'Hello '448 yield flask.request.args['name']449 yield '!'450 return flask.Response(flask.stream_with_context(451 Wrapper(generate())))452 c = app.test_client()453 rv = c.get('/?name=World')454 self.assertEqual(rv.data, 'Hello World!')455 self.assertEqual(called, [42])456457458def suite():459 suite = unittest.TestSuite()460 if flask.json_available:461 suite.addTest(unittest.makeSuite(JSONTestCase))462 suite.addTest(unittest.makeSuite(SendfileTestCase))463 suite.addTest(unittest.makeSuite(LoggingTestCase))464 suite.addTest(unittest.makeSuite(NoImportsTestCase))465 suite.addTest(unittest.makeSuite(StreamingTestCase))466 return suite
modified:flask/__init__.py+2 added-1 removed
20 unmodified lines
21from .app import Flask, Request, Response22from .config import Config23from .helpers import url_for, jsonify, json_available, flash, \24 send_file, send_from_directory, get_flashed_messages, \25 get_template_attribute, make_response, safe_join25 get_template_attribute, make_response, safe_join, \26 stream_with_context27from .globals import current_app, g, request, session, _request_ctx_stack, \28 _app_ctx_stack29from .ctx import has_request_context, has_app_context, \30 after_this_request
14 unmodified lines
modified:flask/ctx.py+38 added-26 removed
20 unmodified lines
21 """A plain object."""22 pass232425def _push_app_if_necessary(app):26 top = _app_ctx_stack.top27 if top is None or top.app != app:28 ctx = app.app_context()29 ctx.push()30 return ctx313225def after_this_request(f):26 """Executes a function after this request. This is useful to modify27 response objects. The function is passed the response object and has28 to return the same or a new one.
72 unmodified lines
101 def __init__(self, app):102 self.app = app103 self.url_adapter = app.create_url_adapter(None)104105 # Like request context, app contexts can be pushed multiple times106 # but there a basic "refcount" is enough to track them.107 self._refcnt = 0108109 def push(self):110 """Binds the app context to the current context."""111 self._refcnt += 1112 _app_ctx_stack.push(self)113114 def pop(self, exc=None):115 """Pops the app context."""116 self._refcnt -= 1117 if self._refcnt <= 0:119 if exc is None:120 exc = sys.exc_info()[1]121 self.app.do_teardown_appcontext(exc)118 if exc is None:119 exc = sys.exc_info()[1]120 self.app.do_teardown_appcontext(exc)121 rv = _app_ctx_stack.pop()122 assert rv is self, 'Popped wrong app context. (%r instead of %r)' \123 % (rv, self)124
1 unmodified line
126 self.push()127 return self128129 def __exit__(self, exc_type, exc_value, tb):131 self.pop()130 self.pop(exc_value)131132133class RequestContext(object):134 """The request context contains all request relevant information. It is
32 unmodified lines
167 self.g = app.request_globals_class()168 self.flashes = None169 self.session = None170171 # Request contexts can be pushed multiple times and interleaved with172 # other request contexts. Now only if the last level is popped we173 # get rid of them. Additionally if an application context is missing174 # one is created implicitly so for each level we add this information175 self._implicit_app_ctx_stack = []176177 # indicator if the context was preserved. Next time another context178 # is pushed the preserved context is popped.179 self.preserved = False180176 # Indicates if pushing this request context also triggered the pushing177 # of an application context. If it implicitly pushed an application178 # context, it will be stored there179 self._pushed_application_context = None180181 # Functions that should be executed after the request on the response182 # object. These will be called before the regular "after_request"183 # functions.184 self._after_request_functions = []
36 unmodified lines
221 top.pop()222223 # Before we push the request context we have to ensure that there224 # is an application context.225 self._pushed_application_context = _push_app_if_necessary(self.app)225 app_ctx = _app_ctx_stack.top226 if app_ctx is None or app_ctx.app != self.app:227 app_ctx = self.app.app_context()228 app_ctx.push()229 self._implicit_app_ctx_stack.append(app_ctx)230 else:231 self._implicit_app_ctx_stack.append(None)232233 _request_ctx_stack.push(self)234235 # Open the session at the moment that the request context is
10 unmodified lines
246247 .. versionchanged:: 0.9248 Added the `exc` argument.249 """250 app_ctx = self._implicit_app_ctx_stack.pop()251252 clear_request = False253 if not self._implicit_app_ctx_stack:244 self.preserved = False245 if exc is None:246 exc = sys.exc_info()[1]247 self.app.do_teardown_request(exc)254 self.preserved = False255 if exc is None:256 exc = sys.exc_info()[1]257 self.app.do_teardown_request(exc)258 clear_request = True259260 rv = _request_ctx_stack.pop()261 assert rv is self, 'Popped wrong request context. (%r instead of %r)' \262 % (rv, self)263264 # get rid of circular dependencies at the end of the request265 # so that we don't require the GC to be active.266 if clear_request:254 rv.request.environ['werkzeug.request'] = None267 rv.request.environ['werkzeug.request'] = None268269 # Get rid of the app as well if necessary.257 if self._pushed_application_context:258 self._pushed_application_context.pop(exc)259 self._pushed_application_context = None270 if app_ctx is not None:271 app_ctx.pop(exc)272273 def __enter__(self):274 self.push()275 return self
20 unmodified lines
modified:flask/helpers.py+73 added
19 unmodified lines
20from zlib import adler3221from threading import RLock22from werkzeug.routing import BuildError23from werkzeug.urls import url_quote24from functools import update_wrapper2526# try to load the best simplejson implementation available. If JSON27# is not installed, we add a failing class.28json_available = True
63 unmodified lines
92 'is not provided.'93 return view_func.__name__949596def stream_with_context(generator_or_function):97 """Request contexts disappear when the response is started on the server.98 This is done for efficiency reasons and to make it less likely to encounter99 memory leaks with badly written WSGI middlewares. The downside is that if100 you are using streamed responses, the generator cannot access request bound101 information any more.102103 This function however can help you keep the context around for longer::104105 from flask import stream_with_context, request, Response106107 @app.route('/stream')108 def streamed_response():109 @stream_with_context110 def generate():111 yield 'Hello '112 yield request.args['name']113 yield '!'114 return Response(generate())115116 Alternatively it can also be used around a specific generator:117118 from flask import stream_with_context, request, Response119120 @app.route('/stream')121 def streamed_response():122 def generate():123 yield 'Hello '124 yield request.args['name']125 yield '!'126 return Response(stream_with_context(generate()))127128 .. versionadded:: 0.9129 """130 try:131 gen = iter(generator_or_function)132 except TypeError:133 def decorator(*args, **kwargs):134 gen = generator_or_function()135 return stream_with_context(gen)136 return update_wrapper(decorator, generator_or_function)137138 def generator():139 ctx = _request_ctx_stack.top140 if ctx is None:141 raise RuntimeError('Attempted to stream with context but '142 'there was no context in the first place to keep around.')143 with ctx:144 # Dummy sentinel. Has to be inside the context block or we're145 # not actually keeping the context around.146 yield None147148 # The try/finally is here so that if someone passes a WSGI level149 # iterator in we're still running the cleanup logic. Generators150 # don't need that because they are closed on their destruction151 # automatically.152 try:153 for item in gen:154 yield item155 finally:156 if hasattr(gen, 'close'):157 gen.close()158159 # The trick is to start the generator. Then the code execution runs until160 # the first dummy None is yielded at which point the context was already161 # pushed. This item is discarded. Then when the iteration continues the162 # real generator is executed.163 wrapped_g = generator()164 wrapped_g.next()165 return wrapped_g166167168def jsonify(*args, **kwargs):169 """Creates a :class:`~flask.Response` with the JSON representation of170 the given arguments with an `application/json` mimetype. The arguments171 to this function are the same as to the :class:`dict` constructor.
722 unmodified lines
modified:CHANGES+2 added
69 unmodified lines
70 be used on creation of the :data:`~flask.g` instance of each request.71- Added `required_methods` attribute to view functions to force-add methods72 on registration.73- Added :func:`flask.after_this_request`.74- Added :func:`flask.stream_with_context` and the ability to push contexts75 multiple times without producing unexpected behavior.7677Version 0.8.178-------------79
294 unmodified lines