Flask Command Line API
Flask built its command-line tool on Click.
ThroughflaskRun applications and manage tasks with commands.
All CLI classes are inflask.cliin the module.
FlaskGroup
Flask's main command group. ViaflaskCommand usage.
| Parameter | Description |
|---|---|
| add_default_commands=True | Whether to add default commands such as run, shell, routes |
| create_app=None | The app factory function, returns a Flask instance |
| add_version_option=True | Whether to add the --version option |
| load_dotenv=True | Whether to load .env and .flaskenv files |
| set_debug_flag=True | Whether to set the debug flag based on environment variables |
AppGroup
Base class for application and blueprint CLI command groups. Byapp.cliorbp.cliAdd custom commands.
| Methods | Description |
|---|---|
| command(*args, **kwargs) | Register CLI commands. By default, automatically wraps with_appcontext |
| group(*args, **kwargs) | Register sub-command groups. By default, AppGroup is used as the group class |
AppGroup.command() enabled by defaultwith_appcontext=True, meaning your command functions automatically have the application context. If not needed, passwith_appcontext=False。
ScriptInfo
Stores the information of the script runtime, used to load the application. Usually no manual operation is needed.
| Property | Description |
|---|---|
| app_import_path | Application import path (--app option value) |
| create_app | Application factory function |
| data | A dictionary of arbitrary additional data |
| load_app() | Load and return the Flask application instance |
Utility functions
| Function | Description |
|---|---|
| with_appcontext(f) | Decorator. Ensures the decorated function runs in the application context |
| pass_script_info(f) | Decorator. Passes the ScriptInfo instance to the function as the first argument |
| load_dotenv(path) | Load environment variables from the .env file |
Default commands
| Command | Description | Common Parameters |
|---|---|---|
| flask run | Start the development server | --host, --port, --debug, --reload/--no-reload |
| flask shell | Launch an interactive Python Shell | Automatically load context variables such as app, g |
| flask routes | List all registered routes | --sort (endpoint/methods/domain/rule/match), --all-methods |
Standard options
| Options | Description |
|---|---|
| -A / --app IMPORT | Specify the application module and instance, such as "app:create_app()" |
| --debug / --no-debug | Enable/disable debug mode |
| -e / --env-file FILE | Specify the path to the .env file |
| --version | Display Flask and dependency versions |
Code Examples
Example
from flask import Flask
app = Flask(__name__)
# Register custom commands
@app.cli.command("init-db")
def init_db_command():
"""Initialize the database"""
print("Database initialized.")
# Register a command with arguments
@app.cli.command("greet")
@app.cli.option("--name", "-n", default="EXAMPLE", help="Greeting target")
def greet_command(name):
"""Send a greeting"""
print(f"Hello, {name}!")
# Register a subcommand group
user_cli = app.cli.group("user")
@user_cli.command("list")
def list_users():
"""List all users"""
print("Listing users...")
@user_cli.command("create")
@user_cli.option("--username", required=True)
def create_user(username):
"""Create a new user"""
print(f"Creating user: {username}")
# Usage:
# flask init-db
# flask greet --name World
# flask user list
# flask user create --username example
app = Flask(__name__)
# Register custom commands
@app.cli.command("init-db")
def init_db_command():
"""Initialize the database"""
print("Database initialized.")
# Register a command with arguments
@app.cli.command("greet")
@app.cli.option("--name", "-n", default="EXAMPLE", help="Greeting target")
def greet_command(name):
"""Send a greeting"""
print(f"Hello, {name}!")
# Register a subcommand group
user_cli = app.cli.group("user")
@user_cli.command("list")
def list_users():
"""List all users"""
print("Listing users...")
@user_cli.command("create")
@user_cli.option("--username", required=True)
def create_user(username):
"""Create a new user"""
print(f"Creating user: {username}")
# Usage:
# flask init-db
# flask greet --name World
# flask user list
# flask user create --username example