{"record":{"id":"7bc604da45dad3e1","repo":"pallets/flask","slug":"copy-current-request-context-can-only-be-used-wh","errorCode":null,"errorMessage":"'copy_current_request_context' can only be used when a request context is active, such as in a view function.","messagePattern":"'copy_current_request_context' 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":196,"sourceCode":"        from flask import copy_current_request_context\n\n        @app.route('/')\n        def index():\n            @copy_current_request_context\n            def do_some_work():\n                # do some work here, it can access flask.request or\n                # flask.session like you would otherwise in the view function.\n                ...\n            gevent.spawn(do_some_work)\n            return 'Regular response'\n\n    .. versionadded:: 0.10\n    \"\"\"\n    # Store the context that was active when the decorator was applied.\n    original = _cv_app.get(None)\n\n    if original is None:\n        raise RuntimeError(\n            \"'copy_current_request_context' can only be used when a\"\n            \" request context is active, such as in a view function.\"\n        )\n\n    def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:\n        # Copy the context before pushing, so each worker acts independently.\n        with original.copy() as ctx:\n            return ctx.app.ensure_sync(f)(*args, **kwargs)\n\n    return update_wrapper(wrapper, f)  # type: ignore[return-value]\n\n\ndef has_request_context() -> bool:\n    \"\"\"Test if an app context is active and if it has request information.\n\n    .. code-block:: python\n\n        from flask import has_request_context, request","sourceCodeStart":178,"sourceCodeEnd":214,"githubUrl":"https://github.com/pallets/flask/blob/3596b1ab61cea85edb8970e83ff61daa073facf8/src/flask/ctx.py#L178-L214","documentation":"copy_current_request_context(f) stores the app context active at decoration time via _cv_app.get(None). If original is None (no context active when the decorator is applied), it raises RuntimeError. The decorator must capture an existing request context so each spawned worker can run a copy of it.","triggerScenarios":"Applying @copy_current_request_context to a function at module import time or anywhere outside an active request/app context. The decorator executes _cv_app.get(None) at decoration time, so the context must already be pushed then.","commonSituations":"Decorating a top-level background function (no active context at import). Forgetting the decorator must be applied inside the view that spawns the worker. Using it in code paths that run before any request is pushed.","solutions":["Apply copy_current_request_context inside the view function where the request context is active, then spawn the worker.","Alternatively define the worker function inside the view and decorate it there so the context is captured correctly.","In tests, push app.test_request_context() before applying the decorator."],"exampleFix":"# before\n@copy_current_request_context\ndef do_work(): ...   # decorated at import -> RuntimeError\n\n@app.route('/')\ndef index():\n    gevent.spawn(do_work)\n    return 'ok'\n\n# after\n@app.route('/')\ndef index():\n    @copy_current_request_context\n    def do_work(): ...\n    gevent.spawn(do_work)\n    return 'ok'","handlingStrategy":"type-guard","validationCode":"from flask import has_request_context\n\ndef can_copy_request_context() -> bool:\n    return has_request_context()","typeGuard":"from flask import has_request_context\n\ndef in_request_context() -> bool:\n    return has_request_context()","tryCatchPattern":"try:\n    @copy_current_request_context\n    def worker(): ...\nexcept RuntimeError:\n    # fall back to passing explicit args instead of relying on request/session\n    pass","preventionTips":["Apply copy_current_request_context inside the view that spawns the worker.","Prefer passing explicit data to background tasks over relying on copied context."],"tags":["flask","request-context","concurrency","lifecycle"],"backgroundTag":null,"analyzedSha":"3596b1ab61cea85edb8970e83ff61daa073facf8","analyzedAt":"2026-08-11T20:11:52.622Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}