{"record":{"id":"bc8a3c7c21374fcf","repo":"pallets/flask","slug":"after-this-request-can-only-be-used-when-a-reque","errorCode":null,"errorMessage":"'after_this_request' can only be used when a request context is active, such as in a view function.","messagePattern":"'after_this_request' can only be used when a request context is active, such as in a view function\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/flask/ctx.py","lineNumber":142,"sourceCode":"    request context, rather than during setup.\n\n    .. code-block:: python\n\n        @app.route(\"/\")\n        def index():\n            @after_this_request\n            def add_header(response):\n                response.headers[\"X-Foo\"] = \"Parachute\"\n                return response\n\n            return \"Hello, World!\"\n\n    .. versionadded:: 0.9\n    \"\"\"\n    ctx = _cv_app.get(None)\n\n    if ctx is None or not ctx.has_request:\n        raise RuntimeError(\n            \"'after_this_request' can only be used when a request\"\n            \" context is active, such as in a view function.\"\n        )\n\n    ctx._after_request_functions.append(f)\n    return f\n\n\nF = t.TypeVar(\"F\", bound=t.Callable[..., t.Any])\n\n\ndef copy_current_request_context(f: F) -> F:\n    \"\"\"Decorate a function to run inside the current request context. This can\n    be used when starting a background task, otherwise it will not see the app\n    and request objects that were active in the parent.\n\n    .. warning::\n","sourceCodeStart":124,"sourceCodeEnd":160,"githubUrl":"https://github.com/pallets/flask/blob/3596b1ab61cea85edb8970e83ff61daa073facf8/src/flask/ctx.py#L124-L160","documentation":"after_this_request(f) reads the current app context from _cv_app. If ctx is None (no app context) or ctx.has_request is False (an app context is active but no request is bound to it), it raises RuntimeError. The function only makes sense within an active request because it queues f onto the current request's after-request chain.","triggerScenarios":"Calling after_this_request(...) outside a view function—e.g. at import time, in a background thread without a request context, in a shell command, or in an app-context-only block (with app.app_context() but no test_request_context/request). The check is ctx is None or not ctx.has_request.","commonSituations":"Registering a cleanup hook from a module-level function. Using after_this_request inside a teardown or before_first_request handler. Background workers spawned without copying the request context.","solutions":["Move the after_this_request call inside a view function where a request context is active.","For background work, wrap the worker in copy_current_request_context and call after_this_request from within that copied context.","In tests, push a request context with app.test_request_context() before invoking code that uses after_this_request."],"exampleFix":"# before\n@app.route('/')\ndef index():\n    return 'hi'\n\nafter_this_request(add_header)  # at module level -> RuntimeError\n\n# after\n@app.route('/')\ndef index():\n    after_this_request(add_header)\n    return 'hi'","handlingStrategy":"type-guard","validationCode":"from flask import has_request_context\n\ndef safe_after_this_request(f):\n    if not has_request_context():\n        raise RuntimeError('after_this_request requires a request context')\n    from flask import after_this_request\n    return after_this_request(f)","typeGuard":"from flask import has_request_context\n\ndef in_request_context() -> bool:\n    return has_request_context()","tryCatchPattern":"try:\n    after_this_request(add_header)\nexcept RuntimeError:\n    # queue the work another way, e.g. store on g or defer\n    pass","preventionTips":["Only call after_this_request inside view functions.","Use flask.has_request_context() to guard before calling."],"tags":["flask","request-context","lifecycle"],"backgroundTag":null,"analyzedSha":"3596b1ab61cea85edb8970e83ff61daa073facf8","analyzedAt":"2026-08-11T20:11:52.622Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}