Skip to content
Myr

all teardown callbacks are called despite errors

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 7b00886 · Browse files · 10 files+194 added−80 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+194 added−80 removed

  • tests:+120 added−70 removed
  • other:+74 added−10 removed

10 files+194 added−80 removed

modified:docs/appcontext.rst+2 added-1 removed
161 unmodified lines
162The teardown callbacks are called by the context when it is popped. They are163called even if there is an unhandled exception during dispatch. They may be164called multiple times in some test scenarios. This means there is no guarantee165that any other parts of the request dispatch have run. Be sure to write these166functions in a way that does not depend on other callbacks and will not fail.166functions in a way that does not depend on other callbacks. All callbacks are167called even if any raise an error.168169170How the Context Works171---------------------
16 unmodified lines
modified:src/flask/app.py+23 added-4 removed
34 unmodified lines
35from .globals import app_ctx36from .globals import g37from .globals import request38from .globals import session39from .helpers import _CollectErrors40from .helpers import get_debug_flag41from .helpers import get_flashed_messages42from .helpers import get_load_dotenv43from .helpers import send_from_directory
1386 unmodified lines
14301431 :param exc: An unhandled exception raised while dispatching the request.1432 Passed to each teardown function.14331434 .. versionchanged:: 3.21435 All callbacks are called rather than stopping on the first error.14361437 .. versionchanged:: 0.91438 Added the ``exc`` argument.1439 """1440 collect_errors = _CollectErrors()14411442 for name in chain(ctx.request.blueprints, (None,)):1443 if name in self.teardown_request_funcs:1444 for func in reversed(self.teardown_request_funcs[name]):1445 with collect_errors:1439 self.ensure_sync(func)(exc)1446 self.ensure_sync(func)(exc)14471448 with collect_errors:1441 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1449 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)14501451 collect_errors.raise_any("Errors during request teardown")14521453 def do_teardown_appcontext(1454 self, ctx: AppContext, exc: BaseException | None = None1455 ) -> None:1456 """Called right before the application context is popped. Called by
4 unmodified lines
14611462 :param exc: An unhandled exception raised while the context was active.1463 Passed to each teardown function.14641465 .. versionchanged:: 3.21466 All callbacks are called rather than stopping on the first error.14671468 .. versionadded:: 0.91469 """1470 collect_errors = _CollectErrors()14711472 for func in reversed(self.teardown_appcontext_funcs):1473 with collect_errors:1458 self.ensure_sync(func)(exc)1474 self.ensure_sync(func)(exc)14751476 with collect_errors:1460 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1477 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)14781479 collect_errors.raise_any("Errors during app teardown")14801481 def app_context(self) -> AppContext:1482 """Create an :class:`.AppContext`. When the context is pushed,1483 :data:`.current_app` and :data:`.g` become available.1484
141 unmodified lines
modified:src/flask/ctx.py+16 added-5 removed
8 unmodified lines
9from werkzeug.routing import MapAdapter1011from . import typing as ft12from .globals import _cv_app13from .helpers import _CollectErrors14from .signals import appcontext_popped15from .signals import appcontext_pushed1617if t.TYPE_CHECKING:
464 unmodified lines
482483 if self._push_count > 0:484 return485485 try:486 if self._request is not None:486 collect_errors = _CollectErrors()487488 if self._request is not None:489 with collect_errors:490 self.app.do_teardown_request(self, exc)491492 with collect_errors:493 self._request.close()489 finally:494495 with collect_errors:496 self.app.do_teardown_appcontext(self, exc)497491 _cv_app.reset(self._cv_token)492 self._cv_token = None498 _cv_app.reset(self._cv_token)499 self._cv_token = None500501 with collect_errors:502 appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)503504 collect_errors.raise_any("Errors during context teardown")505506 def __enter__(self) -> te.Self:507 self.push()508 return self509
31 unmodified lines
modified:src/flask/helpers.py+32 added
5 unmodified lines
6import typing as t7from datetime import datetime8from functools import cache9from functools import update_wrapper10from types import TracebackType1112import werkzeug.utils13from werkzeug.exceptions import abort as _wz_abort14from werkzeug.utils import redirect as _wz_redirect
621 unmodified lines
636 if "." in name:637 out.extend(_split_blueprint_path(name.rpartition(".")[0]))638639 return out640641642class _CollectErrors:643 """A context manager that records and silences an error raised within it.644 Used to run all teardown functions, then raise any errors afterward.645 """646647 def __init__(self) -> None:648 self.errors: list[BaseException] = []649650 def __enter__(self) -> None:651 pass652653 def __exit__(654 self,655 exc_type: type[BaseException] | None,656 exc_val: BaseException | None,657 exc_tb: TracebackType | None,658 ) -> bool:659 if exc_val is not None:660 self.errors.append(exc_val)661662 return True663664 def raise_any(self, message: str) -> None:665 """Raise if any errors were collected."""666 if self.errors:667 if sys.version_info >= (3, 11):668 raise BaseExceptionGroup(message, self.errors) # noqa: F821669 else:670 raise self.errors[0]
modified:tests/test_appctx.py+55 added
1import sys23import pytest45import flask6from flask.globals import app_ctx7from flask.testing import FlaskClient8910def test_basic_url_generation(app):11 app.config["SERVER_NAME"] = "localhost"
198 unmodified lines
210 called.append(flask.current_app.name)211212 assert called == ["flask_test", "TEARDOWN"]213 assert not flask.current_app214215216def test_robust_teardown(app: flask.Flask, client: FlaskClient) -> None:217 count = 0218219 @app.teardown_request220 def request_teardown(e: Exception | None) -> None:221 nonlocal count222 count += 1223 raise ValueError("request_teardown")224225 @app.teardown_appcontext226 def app_teardown(e: Exception | None) -> None:227 nonlocal count228 count += 1229 raise ValueError("app_teardown")230231 @app.get("/")232 def index() -> str:233 return ""234235 def request_signal(sender: flask.Flask, exc: Exception | None) -> None:236 nonlocal count237 count += 1238 raise ValueError("request_signal")239240 def app_signal(sender: flask.Flask, exc: Exception | None) -> None:241 nonlocal count242 count += 1243 raise ValueError("app_signal")244245 with (246 flask.request_tearing_down.connected_to(request_signal, app),247 flask.appcontext_tearing_down.connected_to(app_signal, app),248 ):249 if sys.version_info >= (3, 11):250 with pytest.raises(ExceptionGroup, match="context teardown") as exc_info: # noqa: F821251 client.get()252253 assert len(exc_info.value.exceptions) == 2254 eg1, eg2 = exc_info.value.exceptions255 assert isinstance(eg1, ExceptionGroup) # noqa: F821256 assert "request teardown" in eg1.message257 assert len(eg1.exceptions) == 2258 assert isinstance(eg2, ExceptionGroup) # noqa: F821259 assert "app teardown" in eg2.message260 assert len(eg2.exceptions) == 2261 else:262 with pytest.raises(ValueError, match="request_teardown"):263 client.get()264265 assert count == 4
modified:tests/test_basic.py+26 added-24 removed
1418 unmodified lines
1419 flask.url_for("/")142014211422def test_static_files(app, client):1423 rv = client.get("/static/index.html")1424 assert rv.status_code == 2001425 assert rv.data.strip() == b"<h1>Hello World!</h1>"1426 with app.test_request_context():1427 assert flask.url_for("static", filename="index.html") == "/static/index.html"1428 rv.close()1423 with client.get("/static/index.html") as rv:1424 assert rv.status_code == 2001425 assert rv.data.strip() == b"<h1>Hello World!</h1>"1426 with app.test_request_context():1427 assert (1428 flask.url_for("static", filename="index.html") == "/static/index.html"1429 )143014311432def test_static_url_path():1433 app = flask.Flask(__name__, static_url_path="/foo")1434 app.testing = True1434 rv = app.test_client().get("/foo/index.html")1435 assert rv.status_code == 2001436 rv.close()14351436 with app.test_client().get("/foo/index.html") as rv:1437 assert rv.status_code == 20014381439 with app.test_request_context():1440 assert flask.url_for("static", filename="index.html") == "/foo/index.html"144114421443def test_static_url_path_with_ending_slash():1444 app = flask.Flask(__name__, static_url_path="/foo/")1445 app.testing = True1445 rv = app.test_client().get("/foo/index.html")1446 assert rv.status_code == 2001447 rv.close()14461447 with app.test_client().get("/foo/index.html") as rv:1448 assert rv.status_code == 20014491450 with app.test_request_context():1451 assert flask.url_for("static", filename="index.html") == "/foo/index.html"145214531454def test_static_url_empty_path(app):1455 app = flask.Flask(__name__, static_folder="", static_url_path="")1455 rv = app.test_client().open("/static/index.html", method="GET")1456 assert rv.status_code == 2001457 rv.close()14561457 with app.test_client().open("/static/index.html", method="GET") as rv:1458 assert rv.status_code == 200145914601461def test_static_url_empty_path_default(app):1462 app = flask.Flask(__name__, static_folder="")1462 rv = app.test_client().open("/static/index.html", method="GET")1463 assert rv.status_code == 2001464 rv.close()14631464 with app.test_client().open("/static/index.html", method="GET") as rv:1465 assert rv.status_code == 200146614671468def test_static_folder_with_pathlib_path(app):1469 from pathlib import Path14701471 app = flask.Flask(__name__, static_folder=Path("static"))1471 rv = app.test_client().open("/static/index.html", method="GET")1472 assert rv.status_code == 2001473 rv.close()14721473 with app.test_client().open("/static/index.html", method="GET") as rv:1474 assert rv.status_code == 200147514761477def test_static_folder_with_ending_slash():1478 app = flask.Flask(__name__, static_folder="static/")14791480 @app.route("/<path:path>")
6 unmodified lines
14871488def test_static_route_with_host_matching():1489 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1490 c = app.test_client()1490 rv = c.get("http://example.com/static/index.html")1491 assert rv.status_code == 2001492 rv.close()14911492 with c.get("http://example.com/static/index.html") as rv:1493 assert rv.status_code == 20014941495 with app.test_request_context():1496 rv = flask.url_for("static", filename="index.html", _external=True)1497 assert rv == "http://example.com/static/index.html"1498 # Providing static_host without host_matching=True should error.
472 unmodified lines
modified:tests/test_blueprints.py+10 added-10 removed
182 unmodified lines
183 rv = client.get("/admin/")184 assert rv.data == b"Hello from the Admin"185 rv = client.get("/admin/index2")186 assert rv.data == b"Hello from the Admin"187 rv = client.get("/admin/static/test.txt")188 assert rv.data.strip() == b"Admin File"189 rv.close()190 rv = client.get("/admin/static/css/test.css")191 assert rv.data.strip() == b"/* nested file */"192 rv.close()187188 with client.get("/admin/static/test.txt") as rv:189 assert rv.data.strip() == b"Admin File"190191 with client.get("/admin/static/css/test.css") as rv:192 assert rv.data.strip() == b"/* nested file */"193194 # try/finally, in case other tests use this app for Blueprint tests.195 max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]196 try:197 expected_max_age = 3600198 if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == expected_max_age:199 expected_max_age = 7200200 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = expected_max_age201 rv = client.get("/admin/static/css/test.css")202 cc = parse_cache_control_header(rv.headers["Cache-Control"])203 assert cc.max_age == expected_max_age204 rv.close()201202 with client.get("/admin/static/css/test.css") as rv:203 cc = parse_cache_control_header(rv.headers["Cache-Control"])204 assert cc.max_age == expected_max_age205 finally:206 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default207208 with app.test_request_context():
910 unmodified lines
modified:tests/test_helpers.py+29 added-35 removed
30 unmodified lines
313233class TestSendfile:34 def test_send_file(self, app, req_ctx):35 rv = flask.send_file("static/index.html")36 assert rv.direct_passthrough37 assert rv.mimetype == "text/html"3835 with app.open_resource("static/index.html") as f:36 expect = f.read()3738 with flask.send_file("static/index.html") as rv:39 assert rv.direct_passthrough40 assert rv.mimetype == "text/html"41 rv.direct_passthrough = False41 assert rv.data == f.read()42 assert rv.data == expect4343 rv.close()4444 def test_static_file(self, app, req_ctx):45 # Default max_age is None.4647 # Test with static file handler.49 rv = app.send_static_file("index.html")50 assert rv.cache_control.max_age is None51 rv.close()48 with app.send_static_file("index.html") as rv:49 assert rv.cache_control.max_age is None5051 # Test with direct use of send_file.54 rv = flask.send_file("static/index.html")55 assert rv.cache_control.max_age is None56 rv.close()52 with flask.send_file("static/index.html") as rv:53 assert rv.cache_control.max_age is None5455 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 36005657 # Test with static file handler.61 rv = app.send_static_file("index.html")62 assert rv.cache_control.max_age == 360063 rv.close()58 with app.send_static_file("index.html") as rv:59 assert rv.cache_control.max_age == 36006061 # Test with direct use of send_file.66 rv = flask.send_file("static/index.html")67 assert rv.cache_control.max_age == 360068 rv.close()62 with flask.send_file("static/index.html") as rv:63 assert rv.cache_control.max_age == 36006465 # Test with pathlib.Path.71 rv = app.send_static_file(FakePath("index.html"))72 assert rv.cache_control.max_age == 360073 rv.close()66 with app.send_static_file(FakePath("index.html")) as rv:67 assert rv.cache_control.max_age == 36006869 class StaticFileApp(flask.Flask):70 def get_send_file_max_age(self, filename):71 return 10
1 unmodified line
73 app = StaticFileApp(__name__)7475 with app.test_request_context():76 # Test with static file handler.83 rv = app.send_static_file("index.html")84 assert rv.cache_control.max_age == 1085 rv.close()77 with app.send_static_file("index.html") as rv:78 assert rv.cache_control.max_age == 107980 # Test with direct use of send_file.88 rv = flask.send_file("static/index.html")89 assert rv.cache_control.max_age == 1090 rv.close()81 with flask.send_file("static/index.html") as rv:82 assert rv.cache_control.max_age == 108384 def test_send_from_directory(self, app, req_ctx):85 app.root_path = os.path.join(86 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"87 )96 rv = flask.send_from_directory("static", "hello.txt")97 rv.direct_passthrough = False98 assert rv.data.strip() == b"Hello Subdomain"99 rv.close()8889 with flask.send_from_directory("static", "hello.txt") as rv:90 rv.direct_passthrough = False91 assert rv.data.strip() == b"Hello Subdomain"929394class TestUrlFor:95 def test_url_for_with_anchor(self, app, req_ctx):96 @app.route("/")97 def index():
212 unmodified lines
310 return flask.Response(gen())311312 # response is closed without reading stream313 client.get().close()314315 # response stream is read316 with client.get() as rv:323 assert client.get().text == "flask"317 assert rv.text == "flask"318319 # same as above, but with client context preservation320 with client:321 client.get().close()322329 with client:330 assert client.get().text == "flask"323 with client, client.get() as rv:324 assert rv.text == "flask"325326327class TestHelpers:328 @pytest.mark.parametrize(
49 unmodified lines
modified:tests/test_testing.py-1 removed
74 unmodified lines
75 def index():76 return flask.request.remote_addr7778 builder = EnvironBuilder(app, path="/index", method="GET")79 request.addfinalizer(builder.close)7980 rv = client.open(builder)81 assert rv.data == b"127.0.0.1"82
302 unmodified lines
modified:CHANGES.rst+1 added
12 unmodified lines
13 ``AppContext`` as the first parameter, instead of using the proxy objects.14 If subclasses were overriding these methods, the old signature is detected,15 shows a deprecation warning, and will continue to work during the16 deprecation period. :issue:`5815`17- All teardown callbacks are called, even if any raise an error. :pr:`5928`18- The ``should_ignore_error`` is deprecated. Handle errors as needed in19 teardown handlers instead. :issue:`5816`20- ``template_filter``, ``template_test``, and ``template_global`` decorators21 can be used without parentheses. :issue:`5729`
1642 unmodified lines