python runtime_error ai_generated true

RuntimeError: Working outside of application context.

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active
3.x active

Root Cause

Accessing Flask's current_app or other context-local proxies without an active application context, common in background threads, CLI scripts, or Celery tasks.

generic

中文

在没有活动应用程序上下文的情况下访问 Flask 的 current_app 或其他上下文局部代理,常见于后台线程、CLI 脚本或 Celery 任务中。

Workarounds

  1. 95% success
    from flask import current_app
    with app.app_context():
        print(current_app.config['SECRET_KEY'])
  2. 90% success
    def worker():
        with app.app_context():
            # do work
            pass

Dead Ends

Common approaches that don't work:

  1. 55% fail

    test_request_context is meant for tests and doesn't push a proper app context for production use, leading to subtle bugs.

  2. 90% fail

    This config only affects exception propagation, not context availability.