From 913b2b6a3599a657825c3fb48aa5b1cf62b91ed1 Mon Sep 17 00:00:00 2001 From: Kadir Can Ozden <101993364+bysiber@users.noreply.github.com> Date: Fri, 20 Feb 2026 03:49:10 +0300 Subject: [PATCH] ensure context cleanup runs even if teardown raises --- src/flask/ctx.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/flask/ctx.py b/src/flask/ctx.py index 8876efd0..849e6c8a 100644 --- a/src/flask/ctx.py +++ b/src/flask/ctx.py @@ -484,13 +484,17 @@ class AppContext: try: if self._request is not None: - self.app.do_teardown_request(self, exc) - self._request.close() + try: + self.app.do_teardown_request(self, exc) + finally: + self._request.close() finally: - self.app.do_teardown_appcontext(self, exc) - _cv_app.reset(self._cv_token) - self._cv_token = None - appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync) + try: + self.app.do_teardown_appcontext(self, exc) + finally: + _cv_app.reset(self._cv_token) + self._cv_token = None + appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync) def __enter__(self) -> te.Self: self.push()