pallets/flask · error · RuntimeError

'copy_current_request_context' can only be used when a…

Error message

'copy_current_request_context' can only be used when a request context is active, such as in a view function.

What it means

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.

Solutions

  1. Apply copy_current_request_context inside the view function where the request context is active, then spawn the worker.
  2. Alternatively define the worker function inside the view and decorate it there so the context is captured correctly.
  3. In tests, push app.test_request_context() before applying the decorator.

Example fix

# before
@copy_current_request_context
def do_work(): ...   # decorated at import -> RuntimeError

@app.route('/')
def index():
    gevent.spawn(do_work)
    return 'ok'

# after
@app.route('/')
def index():
    @copy_current_request_context
    def do_work(): ...
    gevent.spawn(do_work)
    return 'ok'
Defensive patterns

Strategy: type-guard

Validate before calling

from flask import has_request_context

def can_copy_request_context() -> bool:
    return has_request_context()

Type guard

from flask import has_request_context

def in_request_context() -> bool:
    return has_request_context()

Try / catch

try:
    @copy_current_request_context
    def worker(): ...
except RuntimeError:
    # fall back to passing explicit args instead of relying on request/session
    pass

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of pallets/flask@3596b1ab61 (2026-08-11). Data as JSON: /api/errors/7bc604da45dad3e1. Report an issue: GitHub.

Appendix: source

Thrown at src/flask/ctx.py:196

        from flask import copy_current_request_context

        @app.route('/')
        def index():
            @copy_current_request_context
            def do_some_work():
                # do some work here, it can access flask.request or
                # flask.session like you would otherwise in the view function.
                ...
            gevent.spawn(do_some_work)
            return 'Regular response'

    .. versionadded:: 0.10
    """
    # Store the context that was active when the decorator was applied.
    original = _cv_app.get(None)

    if original is None:
        raise RuntimeError(
            "'copy_current_request_context' can only be used when a"
            " request context is active, such as in a view function."
        )

    def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
        # Copy the context before pushing, so each worker acts independently.
        with original.copy() as ctx:
            return ctx.app.ensure_sync(f)(*args, **kwargs)

    return update_wrapper(wrapper, f)  # type: ignore[return-value]


def has_request_context() -> bool:
    """Test if an app context is active and if it has request information.

    .. code-block:: python

        from flask import has_request_context, request

View on GitHub (pinned to 3596b1ab61)