python runtime_error ai_generated true

RuntimeError:在应用程序上下文之外工作。

RuntimeError: Working outside of application context.

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

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-01-15首次发现

版本兼容性

版本状态引入弃用备注
2.x active
3.x active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 55% 失败

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

  2. 90% 失败

    This config only affects exception propagation, not context availability.