Access Flask app context in CLI command
Flask's docs about the CLI discuss this.
@app.cli.command()
automatically ensures there's an app context when the command runs. However, this is less convenient to use when using an app factory because you don't have access to the app when defining the command.
When using the app factory, you use @click.command()
and app.cli.add_command()
to separate defining and registering the command, but @click.command
doesn't know about the app context. Use the @with_appcontext
decorator to ensure the command runs in an app context.
@click.command()@with_appcontextdef my_command(): config = current_app.config click.echo(config["TEST_VARIABLE"])def create_app(): app = Flask(__name__) ... app.cli.add_command(my_command) ... return app
$ flask my-commandTESTVALUE