new debug/test preserve context implementation
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 3635583 · 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
Provenance
- Commit
84c7220- Tree
ccad9fc- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
3635583
10 files changed+84 added−220 removed
modified:docs/config.rst+3 added-8 removed
124 unmodified lines125 is enabled.126 127 Default: ``None``128 129-.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION130-131- 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.134-135- Default: ``None``136-129 .. py:data:: TRAP_HTTP_EXCEPTIONS130 131 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 a250 unmodified lines383 cookie's ``SameSite`` option.384 385 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.386 387+.. versionchanged:: 2.2388+ Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.389 390+391 Configuring from Python Files392 -----------------------------393 394 Configuration becomes more useful if you can store it in a separate file,387 unmodified linesmodified:docs/reqcontext.rst-19 removed
217 unmodified lines218 #. :data:`request_tearing_down` is sent after the219 :meth:`~Flask.teardown_request` functions are called.220 221 222-Context Preservation on Error223------------------------------224-225-At the end of a request, the request context is popped and all data226-associated with it is destroyed. If an error occurs during development,227-it is useful to delay destroying the data for debugging purposes.228-229-When the development server is running in development mode (the230-``--env`` option is set to ``'development'``), the error and data will231-be preserved and shown in the interactive debugger.232-233-This behavior can be controlled with the234-:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it235-defaults to ``True`` in the development environment.236-237-Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it238-will cause your application to leak memory on exceptions.239-240-222 .. _notes-on-proxies:223 224 Notes On Proxies225 ----------------21 unmodified linesmodified:src/flask/app.py+7 added-16 removed
329 unmodified lines330 "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 lines581 if rv is not None:582 return rv583 return self.testing or self.debug584 586- @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.591-592- .. versionadded:: 0.7593- """594- rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]595- if rv is not None:596- return rv597- return self.debug598-585 @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 lines2286 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)2293+2304- 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)2296 2297+ ctx.pop(error)2298+2299 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 linesmodified:src/flask/ctx.py+19 added-50 removed
287 unmodified lines288 When the request context is popped, it will evaluate all the289 functions registered on the application for teardown execution290 (:meth:`~flask.Flask.teardown_request`).291 292- 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.301-302- 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 """299 300 def __init__(301 self,19 unmodified lines321 # 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"]] = []324 333- # indicator if the context was preserved. Next time another context334- # is pushed the preserved context is popped.335- self.preserved = False336-337- # remembers the exception for pop if there is one in case the context338- # preservation kicks in.339- self._preserved_exc = None340-325 # 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 lines383 except HTTPException as e:384 self.request.routing_exception = e385 386 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)415-387 # 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 lines424 clear_request = False425 426 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 lines449 rv is self450 ), f"Popped wrong request context. ({rv!r} instead of {self!r})"451 452 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 warnings458 459+ 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)465+466 def __enter__(self) -> "RequestContext":467 self.push()468 return self469 2 unmodified lines472 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)477 478 def __repr__(self) -> str:479 return (480 f"<{type(self).__name__} {self.request.url!r}"2 unmodified linesmodified:src/flask/scaffold.py-7 removed
598 unmodified lines599 When a teardown function was called because of an exception it will600 be passed an error object.601 602 The return values of teardown functions are ignored.603-604- .. admonition:: Debug Note605-606- 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 linesmodified:src/flask/testing.py+24 added-19 removed
1 import typing as t2 from contextlib import contextmanager3+from contextlib import ExitStack4 from copy import copy5 from types import TracebackType6 7 import werkzeug.test100 unmodified lines108 Basic usage is outlined in the :doc:`/testing` chapter.109 """110 111 application: "Flask"111- preserve_context = False112 113 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 lines175 headers = resp.get_wsgi_headers(c.request.environ)176 self.cookie_jar.extract_wsgi(c.request.environ, headers)177 178 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}180 181+ if self.preserve_context:182+ out["werkzeug.debug.preserve_context"] = self._new_contexts.append183+184+ return out185+186 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 lines217 else:218 # request is None219 request = self._request_from_builder_args(args, kwargs)220 221+ # 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()225+217- return super().open(226+ response = super().open(227 request,228 buffered=buffered,229 follow_redirects=follow_redirects,230 )231 232+ # 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)236+237+ return response238+239 def __enter__(self) -> "FlaskClient":240 if self.preserve_context:241 raise RuntimeError("Cannot nest client invocations")242 self.preserve_context = True5 unmodified lines248 exc_value: t.Optional[BaseException],249 tb: t.Optional[TracebackType],250 ) -> None:251 self.preserve_context = False252+ self._context_stack.close()253 237- # 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.top254 244- if top is not None and top.preserved:245- top.pop()246- else:247- break248-249-255 class 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 linesmodified:tests/test_basic.py+2 added-58 removed
926 unmodified lines927 @app.route("/")928 def broken_func():929 raise KeyboardInterrupt()930 931- with client:932- with pytest.raises(KeyboardInterrupt):933- client.get("/")931+ with pytest.raises(KeyboardInterrupt):932+ client.get("/")933 935- ctx = flask._request_ctx_stack.top936- assert ctx.preserved937- assert type(ctx._preserved_exc) is KeyboardInterrupt934 939-935 def test_before_request_and_routing_errors(app, client):936 @app.before_request937 def attach_something():938 flask.g.something = "value"824 unmodified lines1763 assert client.get("/bar/").data == b"bar"1764 assert client.get("/bar/123").data == b"123"1765 1766 1772-def test_preserve_only_once(app, client):1773- app.debug = True1774-1775- @app.route("/fail")1776- def fail_func():1777- 1 // 01778-1779- for _x in range(3):1780- with pytest.raises(ZeroDivisionError):1781- client.get("/fail")1782-1783- 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 None1789-1790-1791-def test_preserve_remembers_exception(app, client):1792- app.debug = True1793- errors = []1794-1795- @app.route("/fail")1796- def fail_func():1797- 1 // 01798-1799- @app.route("/success")1800- def success_func():1801- return "Okay"1802-1803- @app.teardown_request1804- def teardown_handler(exc):1805- errors.append(exc)1806-1807- # After this failure we did not yet call the teardown handler1808- with pytest.raises(ZeroDivisionError):1809- client.get("/fail")1810- assert errors == []1811-1812- # But this request triggers it, and it's an error1813- client.get("/success")1814- assert len(errors) == 21815- assert isinstance(errors[0], ZeroDivisionError)1816-1817- # At this point another request does nothing.1818- client.get("/success")1819- assert len(errors) == 31820- assert errors[1] is None1821-1822-1767 def 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 = 42203 unmodified linesmodified:tests/test_signals.py+11 added-15 removed
121 unmodified lines122 finally:123 flask.got_request_exception.disconnect(record, app)124 125 126-def test_appcontext_signals():127- app = flask.Flask(__name__)126+def test_appcontext_signals(app, client):127 recorded = []128 129 def record_push(sender, **kwargs):130 recorded.append("push")7 unmodified lines138 139 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 lines170 finally:171 flask.message_flashed.disconnect(record, app)172 173 177-def test_appcontext_tearing_down_signal():178- app = flask.Flask(__name__)174+def test_appcontext_tearing_down_signal(app, client):175+ app.testing = False176 recorded = []177 181- def record_teardown(sender, **kwargs):182- recorded.append(("tear_down", kwargs))178+ def record_teardown(sender, exc):179+ recorded.append(exc)180 181 @app.route("/")182 def index():183 1 // 0184 185 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 lines186 187 188 def test_session_transactions_no_null_sessions():189 app = flask.Flask(__name__)190- app.testing = True190 191 with app.test_client() as c:192 with pytest.raises(RuntimeError) as e:193 with c.session_transaction():58 unmodified lines252 with c:253 assert client.get("/").status_code == 404254 255 257-def test_test_client_calls_teardown_handlers(app, client):258- called = []259-260- @app.teardown_request261- def remember(error):262- called.append(error)263-264- with client:265- assert called == []266- client.get("/")267- assert called == []268- assert called == [None]269-270- 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]278-279-256 def test_full_url_request(app, client):257 @app.route("/action", methods=["POST"])258 def action():259 return "x"127 unmodified lines387 388 def 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")393 418- # 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("/")398 399+ # 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_ctxmodified:CHANGES.rst+12 added
40 unmodified lines41 - 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`47 48+ - ``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.57 58+59 Version 2.1.360 -------------61 62 Unreleased1289 unmodified lines