Command Line Interface
The Flask Command Line Interface (CLI) is built on top of the Click library, providing a powerful system for managing your application and creating custom management scripts. It automatically handles application discovery, environment variable loading, and ensures that commands run within the correct application context.
Adding Custom Commands
You can add custom commands directly to your Flask application using the app.cli object. This object is an instance of AppGroup, which ensures that every command it registers is automatically wrapped in an application context.
import click
from flask import Flask
app = Flask(__name__)
@app.cli.command("hello")
@click.argument("name")
def hello_command(name):
click.echo(f"Hello {name}!")
When you run flask hello world, Flask will find your application, push an application context, and then execute the command.
Blueprint Commands
Blueprints can also contribute commands to the CLI. By default, blueprint commands are nested under a group named after the blueprint. You can customize this group name using the cli_group parameter when creating the Blueprint.
from flask import Blueprint
custom_bp = Blueprint("custom", __name__, cli_group="customized")
@custom_bp.cli.command("do-work")
def do_work():
click.echo("Working...")
# Registering the blueprint makes the command available
app.register_blueprint(custom_bp)
In this example, the command is accessible as flask customized do-work. If you set cli_group=None, the commands will be registered directly at the top level of the flask command.
Managing Application Context
Flask uses the AppGroup class (a subclass of click.Group) to manage commands that require access to the application. Most commands registered via app.cli or Blueprint.cli automatically have an application context pushed before they run.
Standalone Commands
If you are defining a standalone Click command that is not attached to a specific app or blueprint, you can use the with_appcontext decorator to ensure current_app and other context-bound globals are available.
import click
from flask import current_app
from flask.cli import with_appcontext
@click.command("print-name")
@with_appcontext
def print_name():
click.echo(f"Running in app: {current_app.name}")
Script Information and App Loading
The ScriptInfo class is a helper object that carries state about the Flask application through the Click context. It is responsible for locating and loading the application instance based on environment variables or command-line options.
When writing advanced CLI extensions, you can access the ScriptInfo object via click.pass_obj or pass_script_info.
from flask.cli import pass_script_info, ScriptInfo
@click.command("check-app")
@pass_script_info
def check_app(info: ScriptInfo):
app = info.load_app()
click.echo(f"Loaded app: {app.import_name}")
The load_app() method ensures the application is only loaded once and handles the logic of searching for app.py, wsgi.py, or the value of the --app option.
Built-in Development Utilities
Flask provides several built-in commands to assist with development. These are implemented in src/flask/cli.py and are available by default in any Flask application.
The Run Command
The flask run command starts the Werkzeug development server. It supports automatic reloading, the interactive debugger, and SSL.
# Start the server with the reloader and debugger enabled
flask --app myapp --debug run
# Start with a specific host and port
flask run --host 0.0.0.0 --port 8080
# Use an ad-hoc SSL certificate (requires 'cryptography')
flask run --cert adhoc
The run_command function in src/flask/cli.py handles the integration with werkzeug.serving.run_simple.
The Shell Command
The flask shell command starts an interactive Python shell. It automatically pushes an application context and populates the shell's namespace with the application instance and other globals defined in app.make_shell_context().
flask shell
The Routes Command
The flask routes command lists all registered URL rules for the application, including their endpoints and supported methods.
flask routes --sort rule
This command iterates over current_app.url_map.iter_rules() to generate a formatted table of your application's routing configuration.
Configuration and Environment
The CLI behavior is heavily influenced by environment variables, which can be loaded from .env and .flaskenv files if python-dotenv is installed.
FLASK_APP: Specifies the application to load. Can be a dotted import path (myapp.app) or a file path (app.py).FLASK_DEBUG: Set to1to enable debug mode, which also enables the reloader and debugger forflask run.FLASK_ENV_FILE: Path to a specific environment file to load.FLASK_SKIP_DOTENV: Set to1to prevent Flask from automatically loading.envand.flaskenvfiles.
The FlaskGroup class handles these options eagerly, ensuring that environment variables are loaded before the application discovery process begins.