Getting Started with the Flask CLI
The Flask command line interface (CLI) is powered by the FlaskGroup class, a specialized Click group that provides built-in commands for running, debugging, and inspecting your application. This tutorial guides you through using these core commands and creating your own custom management script.
Prerequisites
To follow this tutorial, you need the flask package installed in your environment. You should also have a basic understanding of Flask application structures.
Step 1: Create a Sample Application
First, create a file named hello.py with a simple Flask application. This will serve as the target for our CLI commands.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, World!"
@app.route("/api/data")
def get_data():
return {"data": "sample"}
This application defines two routes that we will later inspect using the CLI.
Step 2: Run the Development Server
The most common CLI command is run, which starts the Werkzeug development server. Use the --app option to point Flask to your application file.
flask --app hello run
When you run this, Flask uses FlaskGroup to locate your app and run_command to start the server. You will see output indicating the server is running on http://127.0.0.1:5000.
To enable interactive debugging and automatic reloading when code changes, add the --debug flag:
flask --app hello --debug run
The --debug flag is handled by FlaskGroup during initialization, setting the application's debug state before the server starts.
Step 3: Inspect Application Routes
As your application grows, it becomes useful to see all registered URL rules. The routes command, implemented via routes_command, provides a tabular view of your app's routing table.
flask --app hello routes
By default, this sorts by endpoint. You can change the sorting logic using the --sort option:
flask --app hello routes --sort rule
The routes command automatically filters out internal methods like HEAD and OPTIONS unless you provide the --all-methods flag.
Step 4: Use the Interactive Shell
The shell command opens an interactive Python session with the application context already pushed. This allows you to interact with current_app and other Flask globals directly.
flask --app hello shell
Inside the shell, you can verify the application name:
>>> from flask import current_app
>>> current_app.name
'hello'
The shell_command uses current_app.make_shell_context() to populate the local namespace, making it an ideal environment for testing database queries or configuration values.
Step 5: Create a Custom Management Script
For advanced use cases, you might want to create a standalone script that behaves like the flask command but is tailored to your project. You can achieve this by using FlaskGroup as the class for a Click group.
Create a file named manage.py:
import click
from flask import Flask
from flask.cli import FlaskGroup
def create_my_app():
app = Flask(__name__)
# Additional configuration here
return app
@click.group(cls=FlaskGroup, create_app=create_my_app)
def cli():
"""Management script for my custom application."""
pass
@cli.command("hello-cli")
def hello_cli():
"""A custom command added to the group."""
click.echo("Hello from the custom CLI!")
if __name__ == "__main__":
cli()
In this example:
- We define a factory function
create_my_app. - We pass this factory to
FlaskGroupvia thecreate_appparameter. - Because we use
cls=FlaskGroup, ourcligroup automatically inherits therun,shell, androutescommands. - We add a custom command
hello-clidirectly to the group.
You can now run your custom script directly:
python manage.py hello-cli
python manage.py routes
Summary
By using the built-in CLI, you've learned how to:
- Start a development server with
run. - Inspect your URL map with
routes. - Debug in an active application context with
shell. - Extend the CLI using
FlaskGroupto create custom management scripts.
For further customization, you can explore AppGroup, which ensures that any command added to it automatically runs within a Flask application context.