From 4fc54c8d5f68fe11742698b9d3f0f8bc639bf197 Mon Sep 17 00:00:00 2001 From: Rohan-Salwan Date: Thu, 11 Nov 2021 17:15:00 +0530 Subject: [PATCH] fix issue4333 --- CHANGES.rst | 2 ++ src/flask/ctx.py | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGES.rst b/CHANGES.rst index 4fec7c54..d0bc6751 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -24,6 +24,8 @@ Released 2021-10-04 - Fix the order of ``before_request`` and other callbacks that trigger before the view returns. They are called from the app down to the closest nested blueprint. :issue:`4229` +- Fix ``after_this_request`` fails with a meaningless error when used + outside request context. :issue:`4333` Version 2.0.1 diff --git a/src/flask/ctx.py b/src/flask/ctx.py index 5c064635..0e6ddefc 100644 --- a/src/flask/ctx.py +++ b/src/flask/ctx.py @@ -130,7 +130,14 @@ def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable: .. versionadded:: 0.9 """ - _request_ctx_stack.top._after_request_functions.append(f) + try: + _request_ctx_stack.top._after_request_functions.append(f) + except Exception: + print( + "This decorator can only be used at local scopes " + "when a request context is on the stack. For instance within " + "view functions." + ) return f