我想注册一个在 Flask 应用程序工厂的单独文件中定义的 CLI 命令。此命令需要访问app.config
. 但是,current_app.config
从命令访问会引发RuntimeError: Working outside of application context.
app/__init__.py
from flask import Flask
from app.commands import my_command
def create_app():
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("config.py")
app.add_command(my_command)
return app
instance/config.py
TEST_VARIABLE = "TESTVALUE"
app/commands.py
from flask import current_app
@click.command()
def my_command():
click.echo(current_app.config["TEST_VARIABLE"])
我希望运行flask my_command
输出TESTVALUE
。但是,我收到以下错误:
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
我需要使用with app.app_context():
forcurrent_app
来工作,但我无权访问,app
因为它是在工厂中定义的。如果我@app.cli.command()
在工厂使用,这不会有问题,因为我可以访问app
变量,甚至不需要推送应用程序上下文。
def create_app():
...
@app.cli.command()
def my_command():
click.echo(current_app.config["TEST_VARIABLE"])
...
但是,我想在其他文件中定义我的命令并让它们使用应用程序配置中的值,而这需要将所有命令嵌套在工厂函数中。
我尝试使用命令中的工厂创建一个应用程序,这很有效,但我不认为这样做只是为了访问配置变量是一个好主意。
import click
import app
@click.command()
def my_command():
app_config = app.create_app().config
click.echo(app_config["TEST_VARIABLE"])
使用应用程序工厂模式时,如何定义可以访问应用程序上下文的命令?