Skip to content
Myr

Context preserving is now part of Flask and not the test client. This fixes #326

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 d2eefe2 · Browse files · 5 files+64 added−21 removed
This commit

State

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

Diff stats

5 files+64 added−21 removed

  • other:+64 added−21 removed

5 files+64 added−21 removed

modified:flask/testsuite/basic.py+17 added
902 unmodified lines
903 self.assertEqual(c.get('/foo/').data, 'foo')904 self.assertEqual(c.get('/bar/').data, 'bar')905 self.assertEqual(c.get('/bar/123').data, '123')906907 def test_preserve_only_once(self):908 app = flask.Flask(__name__)909 app.debug = True910911 @app.route('/fail')912 def fail_func():913 1/0914915 c = app.test_client()916 for x in xrange(3):917 with self.assert_raises(ZeroDivisionError):918 c.get('/fail')919920 self.assert_(flask._request_ctx_stack.top is not None)921 flask._request_ctx_stack.pop()922 self.assert_(flask._request_ctx_stack.top is None)923924925class ContextTestCase(FlaskTestCase):926927 def test_context_binding(self):928 app = flask.Flask(__name__)
123 unmodified lines
modified:flask/ctx.py+32 added-3 removed
87 unmodified lines
88 self.g = _RequestGlobals()89 self.flashes = None90 self.session = None9192 # indicator if the context was preserved. Next time another context93 # is pushed the preserved context is popped.94 self.preserved = False9596 self.match_request()9798 # XXX: Support for deprecated functionality. This is doing away with99 # Flask 1.0
17 unmodified lines
117 self.request.routing_exception = e118119 def push(self):120 """Binds the request context to the current context."""121 # If an exception ocurrs in debug mode or if context preservation is122 # activated under exception situations exactly one context stays123 # on the stack. The rationale is that you want to access that124 # information under debug situations. However if someone forgets to125 # pop that context again we want to make sure that on the next push126 # it's invalidated otherwise we run at risk that something leaks127 # memory. This is usually only a problem in testsuite since this128 # functionality is not active in production environments.129 top = _request_ctx_stack.top130 if top is not None and top.preserved:131 top.pop()132133 _request_ctx_stack.push(self)134135 # Open the session at the moment that the request context is136 # available. This allows a custom open_session method to use the
6 unmodified lines
143 """Pops the request context and unbinds it by doing that. This will144 also trigger the execution of functions registered by the145 :meth:`~flask.Flask.teardown_request` decorator.146 """147 self.preserved = False148 self.app.do_teardown_request()132 _request_ctx_stack.pop()149 rv = _request_ctx_stack.pop()150 assert rv is self, 'Popped wrong request context. (%r instead of %r)' \151 % (rv, self)152153 def __enter__(self):154 self.push()155 return self
3 unmodified lines
159 # exception happened. This will allow the debugger to still160 # access the request object in the interactive shell. Furthermore161 # the context can be force kept alive for the test client.162 # See flask.testing for how this works.144 if not self.request.environ.get('flask._preserve_context') and \145 (tb is None or not self.app.preserve_context_on_exception):163 if self.request.environ.get('flask._preserve_context') or \164 (tb is not None and self.app.preserve_context_on_exception):165 self.preserved = True166 else:167 self.pop()168169 def __repr__(self):170 return '<%s \'%s\' [%s] of %s>' % (171 self.__class__.__name__,172 self.request.url,173 self.request.method,174 self.app.name175 )
modified:flask/globals.py+1 added
17 unmodified lines
18 if top is None:19 raise RuntimeError('working outside of request context')20 return getattr(top, name)212223# context locals24_request_ctx_stack = LocalStack()25current_app = LocalProxy(partial(_lookup_object, 'app'))26request = LocalProxy(partial(_lookup_object, 'request'))
2 unmodified lines
modified:flask/testing.py+11 added-18 removed
35 unmodified lines
3637 Basic usage is outlined in the :ref:`testing` chapter.38 """3940 preserve_context = context_preserved = False40 preserve_context = False4142 @contextmanager43 def session_transaction(self, *args, **kwargs):44 """When used in combination with a with statement this opens a
42 unmodified lines
87 headers = resp.get_wsgi_headers(c.request.environ)88 self.cookie_jar.extract_wsgi(c.request.environ, headers)8990 def open(self, *args, **kwargs):91 self._pop_reqctx_if_necessary()91 kwargs.setdefault('environ_overrides', {}) \92 ['flask._preserve_context'] = self.preserve_context9394 as_tuple = kwargs.pop('as_tuple', False)95 buffered = kwargs.pop('buffered', False)96 follow_redirects = kwargs.pop('follow_redirects', False)97 builder = make_test_environ_builder(self.application, *args, **kwargs)98100 old = _request_ctx_stack.top101 try:102 return Client.open(self, builder,103 as_tuple=as_tuple,104 buffered=buffered,105 follow_redirects=follow_redirects)99 return Client.open(self, builder,100 as_tuple=as_tuple,101 buffered=buffered,102 follow_redirects=follow_redirects)106 finally:107 self.context_preserved = _request_ctx_stack.top is not old103104 def __enter__(self):105 if self.preserve_context:106 raise RuntimeError('Cannot nest client invocations')
1 unmodified line
108 return self109110 def __exit__(self, exc_type, exc_value, tb):111 self.preserve_context = False117 self._pop_reqctx_if_necessary()112119 def _pop_reqctx_if_necessary(self):120 if self.context_preserved:121 # we have to use _request_ctx_stack.top.pop instead of122 # _request_ctx_stack.pop since we want teardown handlers123 # to be executed.124 _request_ctx_stack.top.pop()125 self.context_preserved = False113 # on exit we want to clean up earlier. Normally the request context114 # stays preserved until the next request in the same thread comes115 # in. See RequestGlobals.push() for the general behavior.116 top = _request_ctx_stack.top117 if top is not None and top.preserved:118 top.pop()
modified:CHANGES+3 added
44 unmodified lines
45- Added finer control over the session cookie parameters.46- HEAD requests to a method view now automatically dispatch to the `get`47 method if no handler was implemented.48- Implemented the virtual :mod:`flask.ext` package to import extensions from.49- The context preservation on exceptions is now an integral component of50 Flask itself and no longer of the test client. This cleaned up some51 internal logic and lowers the odds of runaway request contexts in unittests.5253Version 0.7.354-------------55
238 unmodified lines