python runtime_error ai_generated true

RuntimeError: Working outside of request context.

ID: python/flask-working-outside-request-context

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —
3.x active — — —

Root Cause

Accessing request, session, or g globals from a background thread, Celery task, or CLI command without an active Flask request context.

generic

中文

在后台线程、Celery任务或CLI命令中访问request、session或g全局变量,但未激活Flask请求上下文。

Workarounds

  1. 85% success
    with app.test_request_context('/path', method='POST'):\n    do_work()
  2. 95% success
    def task(user_id, payload): ...\nuser_id = request.headers.get('X-User-Id')\ntask.delay(user_id, request.json)

Dead Ends

Common approaches that don't work:

  1. 70% fail

    app_context does not push a request context; request, session, and g still raise RuntimeError.

  2. 90% fail

    This only affects exception propagation, not context availability.