pallets/flask · error · RuntimeError

Cannot pop this context

Error message

Cannot pop this context ({self!r}), there is no active context.

What it means

In pop(), after confirming self._cv_token is not None, Flask reads _cv_app.get(None). If that returns None (the context-local variable was reset/cleared) or the token is somehow None, it raises RuntimeError stating there is no active context. This indicates the context stack was emptied externally while a pop was attempted.

Solutions

  1. Use the 'with ctx:' form so Flask manages the context var lifecycle and you never pop a context whose var was cleared.
  2. Avoid sharing context objects across threads/greenlets; each worker should push its own context.
  3. Ensure no code path clears the context var (via token reset) before your pop() runs.

Example fix

# before
ctx.push()
# ... something resets _cv_app (e.g. another pop or thread boundary)
ctx.pop()  # RuntimeError: no active context

# after: keep push/pop on the same thread/flow
ctx.push()
try:
    do_work()  # no nested pop here
finally:
    ctx.pop()
Defensive patterns

Strategy: try-catch

Validate before calling

from flask.globals import _cv_app

def has_active_context() -> bool:
    return _cv_app.get(None) is not None

Type guard

null

Try / catch

try:
    ctx.pop()
except RuntimeError as e:
    if 'no active context' in str(e):
        # context var was cleared externally; reset local state
        ctx._cv_token = None
    else:
        raise

Prevention

When it happens

Trigger: The context var holding the active context was cleared (e.g. by another pop, garbage collection of the token, or running in a thread/async boundary where the context var does not propagate) at the moment pop() reads it. Distinct from error 30 (never pushed) and 32 (wrong context active).

Common situations: Mixing manual context management across threads or greenlets where the context var is thread/async-local. A double-managed context where a prior pop cleared the var. Test harnesses that reset context state between operations.

Related errors


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

Appendix: source

Thrown at src/flask/ctx.py:471

        This context must currently be the active context, otherwise a
        :exc:`RuntimeError` is raised. In some situations, such as streaming or
        testing, the context may have been pushed multiple times. It will only
        trigger cleanup once it has been popped as many times as it was pushed.
        Until then, it will remain the active context.

        :param exc: An unhandled exception that was raised while the context was
            active. Passed to teardown functions.

        .. versionchanged:: 0.9
            Added the ``exc`` argument.
        """
        if self._cv_token is None:
            raise RuntimeError(f"Cannot pop this context ({self!r}), it is not pushed.")

        ctx = _cv_app.get(None)

        if ctx is None or self._cv_token is None:
            raise RuntimeError(
                f"Cannot pop this context ({self!r}), there is no active context."
            )

        if ctx is not self:
            raise RuntimeError(
                f"Cannot pop this context ({self!r}), it is not the active"
                f" context ({ctx!r})."
            )

        self._push_count -= 1

        if self._push_count > 0:
            return

        collect_errors = _CollectErrors()

        if self._request is not None:
            with collect_errors:

View on GitHub (pinned to 3596b1ab61)