Skip to content
Myr

Merge pull request #4666 from pallets/debug-context

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

new preserve context implementation

authored by David Lord · committed by GitHub · parents 57a95e8, 84c7220 · Browse files · 10 files+84 added−220 removed
This commit

State

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

Diff stats

10 files+84 added−220 removed

  • tests:+19 added−101 removed
  • other:+65 added−119 removed

10 files+84 added−220 removed

modified:docs/config.rst+3 added-8 removed
124 unmodified lines
125 is enabled.126127 Default: ``None``128129.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION130131 Don't pop the request context when an exception occurs. If not set, this132 is true if ``DEBUG`` is true. This allows debuggers to introspect the133 request data on errors, and should normally not need to be set directly.134135 Default: ``None``136129.. py:data:: TRAP_HTTP_EXCEPTIONS130131 If there is no handler for an ``HTTPException``-type exception, re-raise it132 to be handled by the interactive debugger instead of returning it as a
250 unmodified lines
383 cookie's ``SameSite`` option.384385 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.386387.. versionchanged:: 2.2388 Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.389390391Configuring from Python Files392-----------------------------393394Configuration becomes more useful if you can store it in a separate file,
387 unmodified lines
modified:docs/reqcontext.rst-19 removed
217 unmodified lines
218#. :data:`request_tearing_down` is sent after the219 :meth:`~Flask.teardown_request` functions are called.220221222Context Preservation on Error223-----------------------------224225At the end of a request, the request context is popped and all data226associated with it is destroyed. If an error occurs during development,227it is useful to delay destroying the data for debugging purposes.228229When the development server is running in development mode (the230``--env`` option is set to ``'development'``), the error and data will231be preserved and shown in the interactive debugger.232233This behavior can be controlled with the234:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it235defaults to ``True`` in the development environment.236237Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it238will cause your application to leak memory on exceptions.239240222.. _notes-on-proxies:223224Notes On Proxies225----------------
21 unmodified lines
modified:src/flask/app.py+7 added-16 removed
329 unmodified lines
330 "ENV": None,331 "DEBUG": None,332 "TESTING": False,333 "PROPAGATE_EXCEPTIONS": None,334 "PRESERVE_CONTEXT_ON_EXCEPTION": None,334 "SECRET_KEY": None,335 "PERMANENT_SESSION_LIFETIME": timedelta(days=31),336 "USE_X_SENDFILE": False,337 "SERVER_NAME": None,
243 unmodified lines
581 if rv is not None:582 return rv583 return self.testing or self.debug584586 @property587 def preserve_context_on_exception(self) -> bool:588 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``589 configuration value in case it's set, otherwise a sensible default590 is returned.591592 .. versionadded:: 0.7593 """594 rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]595 if rv is not None:596 return rv597 return self.debug598585 @locked_cached_property586 def logger(self) -> logging.Logger:587 """A standard Python :class:`~logging.Logger` for the app, with588 the same name as :attr:`name`.
1697 unmodified lines
2286 error = sys.exc_info()[1]2287 raise2288 return response(environ, start_response)2289 finally:2290 if "werkzeug.debug.preserve_context" in environ:2291 environ["werkzeug.debug.preserve_context"](_app_ctx_stack.top)2292 environ["werkzeug.debug.preserve_context"](_request_ctx_stack.top)22932304 if self.should_ignore_error(error):2294 if error is not None and self.should_ignore_error(error):2295 error = None2306 ctx.auto_pop(error)22962297 ctx.pop(error)22982299 def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:2300 """The WSGI server calls the Flask application object as the2301 WSGI application. This calls :meth:`wsgi_app`, which can be2302 wrapped to apply middleware.
2 unmodified lines
modified:src/flask/ctx.py+19 added-50 removed
287 unmodified lines
288 When the request context is popped, it will evaluate all the289 functions registered on the application for teardown execution290 (:meth:`~flask.Flask.teardown_request`).291292 The request context is automatically popped at the end of the request293 for you. In debug mode the request context is kept around if294 exceptions happen so that interactive debuggers have a chance to295 introspect the data. With 0.4 this can also be forced for requests296 that did not fail and outside of ``DEBUG`` mode. By setting297 ``'flask._preserve_context'`` to ``True`` on the WSGI environment the298 context will not pop itself at the end of the request. This is used by299 the :meth:`~flask.Flask.test_client` for example to implement the300 deferred cleanup functionality.301302 You might find this helpful for unittests where you need the303 information from the context local around for a little longer. Make304 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in305 that situation, otherwise your unittests will leak memory.292 The request context is automatically popped at the end of the293 request. When using the interactive debugger, the context will be294 restored so ``request`` is still accessible. Similarly, the test295 client can preserve the context after the request ends. However,296 teardown functions may already have closed some resources such as297 database connections.298 """299300 def __init__(301 self,
19 unmodified lines
321 # get rid of them. Additionally if an application context is missing322 # one is created implicitly so for each level we add this information323 self._implicit_app_ctx_stack: t.List[t.Optional["AppContext"]] = []324333 # indicator if the context was preserved. Next time another context334 # is pushed the preserved context is popped.335 self.preserved = False336337 # remembers the exception for pop if there is one in case the context338 # preservation kicks in.339 self._preserved_exc = None340325 # Functions that should be executed after the request on the response326 # object. These will be called before the regular "after_request"327 # functions.328 self._after_request_functions: t.List[ft.AfterRequestCallable] = []
54 unmodified lines
383 except HTTPException as e:384 self.request.routing_exception = e385386 def push(self) -> None:403 """Binds the request context to the current context."""404 # If an exception occurs in debug mode or if context preservation is405 # activated under exception situations exactly one context stays406 # on the stack. The rationale is that you want to access that407 # information under debug situations. However if someone forgets to408 # pop that context again we want to make sure that on the next push409 # it's invalidated, otherwise we run at risk that something leaks410 # memory. This is usually only a problem in test suite since this411 # functionality is not active in production environments.412 top = _request_ctx_stack.top413 if top is not None and top.preserved:414 top.pop(top._preserved_exc)415387 # Before we push the request context we have to ensure that there388 # is an application context.389 app_ctx = _app_ctx_stack.top390 if app_ctx is None or app_ctx.app != self.app:
33 unmodified lines
424 clear_request = False425426 try:427 if not self._implicit_app_ctx_stack:457 self.preserved = False458 self._preserved_exc = None428 if exc is _sentinel:429 exc = sys.exc_info()[1]430 self.app.do_teardown_request(exc)431
17 unmodified lines
449 rv is self450 ), f"Popped wrong request context. ({rv!r} instead of {self!r})"451452 def auto_pop(self, exc: t.Optional[BaseException]) -> None:484 if self.request.environ.get("flask._preserve_context") or (485 exc is not None and self.app.preserve_context_on_exception486 ):487 self.preserved = True488 self._preserved_exc = exc # type: ignore489 else:490 self.pop(exc)453 """454 .. deprecated:: 2.2455 Will be removed in Flask 2.3.456 """457 import warnings458459 warnings.warn(460 "'ctx.auto_pop' is deprecated and will be removed in Flask 2.3.",461 DeprecationWarning,462 stacklevel=2,463 )464 self.pop(exc)465466 def __enter__(self) -> "RequestContext":467 self.push()468 return self469
2 unmodified lines
472 exc_type: t.Optional[type],473 exc_value: t.Optional[BaseException],474 tb: t.Optional[TracebackType],475 ) -> None:502 # do not pop the request stack if we are in debug mode and an503 # exception happened. This will allow the debugger to still504 # access the request object in the interactive shell. Furthermore505 # the context can be force kept alive for the test client.506 # See flask.testing for how this works.507 self.auto_pop(exc_value)476 self.pop(exc_value)477478 def __repr__(self) -> str:479 return (480 f"<{type(self).__name__} {self.request.url!r}"
2 unmodified lines
modified:src/flask/scaffold.py-7 removed
598 unmodified lines
599 When a teardown function was called because of an exception it will600 be passed an error object.601602 The return values of teardown functions are ignored.603604 .. admonition:: Debug Note605606 In debug mode Flask will not tear down a request on an exception607 immediately. Instead it will keep it alive so that the interactive608 debugger can still access it. This behavior can be controlled609 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.603 """604 self.teardown_request_funcs.setdefault(None, []).append(f)605 return f606
284 unmodified lines
modified:src/flask/testing.py+24 added-19 removed
1import typing as t2from contextlib import contextmanager3from contextlib import ExitStack4from copy import copy5from types import TracebackType67import werkzeug.test
100 unmodified lines
108 Basic usage is outlined in the :doc:`/testing` chapter.109 """110111 application: "Flask"111 preserve_context = False112113 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:114 super().__init__(*args, **kwargs)115 self.preserve_context = False116 self._new_contexts: t.List[t.ContextManager[t.Any]] = []117 self._context_stack = ExitStack()118 self.environ_base = {119 "REMOTE_ADDR": "127.0.0.1",120 "HTTP_USER_AGENT": f"werkzeug/{werkzeug.__version__}",121 }
53 unmodified lines
175 headers = resp.get_wsgi_headers(c.request.environ)176 self.cookie_jar.extract_wsgi(c.request.environ, headers)177178 def _copy_environ(self, other):176 return {177 **self.environ_base,178 **other,179 "flask._preserve_context": self.preserve_context,180 }179 out = {**self.environ_base, **other}180181 if self.preserve_context:182 out["werkzeug.debug.preserve_context"] = self._new_contexts.append183184 return out185186 def _request_from_builder_args(self, args, kwargs):187 kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {}))188 builder = EnvironBuilder(self.application, *args, **kwargs)189
27 unmodified lines
217 else:218 # request is None219 request = self._request_from_builder_args(args, kwargs)220221 # Pop any previously preserved contexts. This prevents contexts222 # from being preserved across redirects or multiple requests223 # within a single block.224 self._context_stack.close()225217 return super().open(226 response = super().open(227 request,228 buffered=buffered,229 follow_redirects=follow_redirects,230 )231232 # Re-push contexts that were preserved during the request.233 while self._new_contexts:234 cm = self._new_contexts.pop()235 self._context_stack.enter_context(cm)236237 return response238239 def __enter__(self) -> "FlaskClient":240 if self.preserve_context:241 raise RuntimeError("Cannot nest client invocations")242 self.preserve_context = True
5 unmodified lines
248 exc_value: t.Optional[BaseException],249 tb: t.Optional[TracebackType],250 ) -> None:251 self.preserve_context = False252 self._context_stack.close()253237 # Normally the request context is preserved until the next238 # request in the same thread comes. When the client exits we239 # want to clean up earlier. Pop request contexts until the stack240 # is empty or a non-preserved one is found.241 while True:242 top = _request_ctx_stack.top254244 if top is not None and top.preserved:245 top.pop()246 else:247 break248249255class FlaskCliRunner(CliRunner):256 """A :class:`~click.testing.CliRunner` for testing a Flask app's257 CLI commands. Typically created using258 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.
30 unmodified lines
modified:tests/test_basic.py+2 added-58 removed
926 unmodified lines
927 @app.route("/")928 def broken_func():929 raise KeyboardInterrupt()930931 with client:932 with pytest.raises(KeyboardInterrupt):933 client.get("/")931 with pytest.raises(KeyboardInterrupt):932 client.get("/")933935 ctx = flask._request_ctx_stack.top936 assert ctx.preserved937 assert type(ctx._preserved_exc) is KeyboardInterrupt934939935def test_before_request_and_routing_errors(app, client):936 @app.before_request937 def attach_something():938 flask.g.something = "value"
824 unmodified lines
1763 assert client.get("/bar/").data == b"bar"1764 assert client.get("/bar/123").data == b"123"176517661772def test_preserve_only_once(app, client):1773 app.debug = True17741775 @app.route("/fail")1776 def fail_func():1777 1 // 017781779 for _x in range(3):1780 with pytest.raises(ZeroDivisionError):1781 client.get("/fail")17821783 assert flask._request_ctx_stack.top is not None1784 assert flask._app_ctx_stack.top is not None1785 # implicit appctx disappears too1786 flask._request_ctx_stack.top.pop()1787 assert flask._request_ctx_stack.top is None1788 assert flask._app_ctx_stack.top is None178917901791def test_preserve_remembers_exception(app, client):1792 app.debug = True1793 errors = []17941795 @app.route("/fail")1796 def fail_func():1797 1 // 017981799 @app.route("/success")1800 def success_func():1801 return "Okay"18021803 @app.teardown_request1804 def teardown_handler(exc):1805 errors.append(exc)18061807 # After this failure we did not yet call the teardown handler1808 with pytest.raises(ZeroDivisionError):1809 client.get("/fail")1810 assert errors == []18111812 # But this request triggers it, and it's an error1813 client.get("/success")1814 assert len(errors) == 21815 assert isinstance(errors[0], ZeroDivisionError)18161817 # At this point another request does nothing.1818 client.get("/success")1819 assert len(errors) == 31820 assert errors[1] is None182118221767def test_get_method_on_g(app_ctx):1768 assert flask.g.get("x") is None1769 assert flask.g.get("x", 11) == 111770 flask.g.x = 42
203 unmodified lines
modified:tests/test_signals.py+11 added-15 removed
121 unmodified lines
122 finally:123 flask.got_request_exception.disconnect(record, app)124125126def test_appcontext_signals():127 app = flask.Flask(__name__)126def test_appcontext_signals(app, client):127 recorded = []128129 def record_push(sender, **kwargs):130 recorded.append("push")
7 unmodified lines
138139 flask.appcontext_pushed.connect(record_push, app)140 flask.appcontext_popped.connect(record_pop, app)141 try:143 with app.test_client() as c:144 rv = c.get("/")145 assert rv.data == b"Hello"142 rv = client.get("/")143 assert rv.data == b"Hello"146 assert recorded == ["push"]144 assert recorded == ["push", "pop"]145 finally:146 flask.appcontext_pushed.disconnect(record_push, app)147 flask.appcontext_popped.disconnect(record_pop, app)
22 unmodified lines
170 finally:171 flask.message_flashed.disconnect(record, app)172173177def test_appcontext_tearing_down_signal():178 app = flask.Flask(__name__)174def test_appcontext_tearing_down_signal(app, client):175 app.testing = False176 recorded = []177181 def record_teardown(sender, **kwargs):182 recorded.append(("tear_down", kwargs))178 def record_teardown(sender, exc):179 recorded.append(exc)180181 @app.route("/")182 def index():183 1 // 0184185 flask.appcontext_tearing_down.connect(record_teardown, app)186 try:190 with app.test_client() as c:191 rv = c.get("/")192 assert rv.status_code == 500193 assert recorded == []194 assert recorded == [("tear_down", {"exc": None})]187 rv = client.get("/")188 assert rv.status_code == 500189 assert len(recorded) == 1190 assert isinstance(recorded[0], ZeroDivisionError)191 finally:192 flask.appcontext_tearing_down.disconnect(record_teardown, app)
modified:tests/test_testing.py+6 added-28 removed
185 unmodified lines
186187188def test_session_transactions_no_null_sessions():189 app = flask.Flask(__name__)190 app.testing = True190191 with app.test_client() as c:192 with pytest.raises(RuntimeError) as e:193 with c.session_transaction():
58 unmodified lines
252 with c:253 assert client.get("/").status_code == 404254255257def test_test_client_calls_teardown_handlers(app, client):258 called = []259260 @app.teardown_request261 def remember(error):262 called.append(error)263264 with client:265 assert called == []266 client.get("/")267 assert called == []268 assert called == [None]269270 del called[:]271 with client:272 assert called == []273 client.get("/")274 assert called == []275 client.get("/")276 assert called == [None]277 assert called == [None, None]278279256def test_full_url_request(app, client):257 @app.route("/action", methods=["POST"])258 def action():259 return "x"
127 unmodified lines
387388def test_client_pop_all_preserved(app, req_ctx, client):389 @app.route("/")390 def index():415 # stream_with_context pushes a third context, preserved by client416 return flask.Response(flask.stream_with_context("hello"))391 # stream_with_context pushes a third context, preserved by response392 return flask.stream_with_context("hello")393418 # req_ctx fixture pushed an initial context, not marked preserved394 # req_ctx fixture pushed an initial context395 with client:396 # request pushes a second request context, preserved by client421 client.get("/")397 rv = client.get("/")398399 # close the response, releasing the context held by stream_with_context400 rv.close()401 # only req_ctx fixture should still be pushed402 assert flask._request_ctx_stack.top is req_ctx
modified:CHANGES.rst+12 added
40 unmodified lines
41- View functions can return generators directly instead of wrapping42 them in a ``Response``. :pr:`4629`43- Add ``stream_template`` and ``stream_template_string`` functions to44 render a template as a stream of pieces. :pr:`4629`45- A new implementation of context preservation during debugging and46 testing. :pr:`4666`4748 - ``request``, ``g``, and other context-locals point to the49 correct data when running code in the interactive debugger50 console. :issue:`2836`51 - Teardown functions are always run at the end of the request,52 even if the context is preserved. They are also run after the53 preserved context is popped.54 - ``stream_with_context`` preserves context separately from a55 ``with client`` block. It will be cleaned up when56 ``response.get_data()`` or ``response.close()`` is called.575859Version 2.1.360-------------6162Unreleased
1289 unmodified lines