Flask Command Line
Introduction
The Flask Command Line Interface (CLI) is a powerful tool that allows you to manage your Flask applications directly from the terminal. It provides commands for running your application, setting up the development environment, and performing various administrative tasks. Understanding the Flask CLI is essential for efficient Flask development and deployment workflows.
In this tutorial, we'll explore the Flask CLI's capabilities, from basic commands to more advanced customizations that can help streamline your development process.
Getting Started with Flask CLI
Flask comes with a built-in command-line interface that's available once you install Flask. The CLI is based on Click, a Python package for creating command-line interfaces.
Basic Commands
The most common command you'll use is flask run
, which starts the development server. Before running this command, you need to tell Flask which application to run by setting the FLASK_APP
environment variable.
On Windows:
set FLASK_APP=app.py
flask run
On macOS/Linux:
export FLASK_APP=app.py
flask run
The output will look something like this:
* Serving Flask app 'app.py'
* Debug mode: off
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
Development Mode
During development, it's useful to enable debug mode, which activates the debugger, automatic reloader, and provides detailed error messages:
On Windows:
set FLASK_APP=app.py
set FLASK_DEBUG=1
flask run
On macOS/Linux:
export FLASK_APP=app.py
export FLASK_DEBUG=1
flask run
Alternatively, you can use the --debug
flag:
flask run --debug
Output with debug mode enabled:
* Serving Flask app 'app.py'
* Debug mode: on
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
Common Flask CLI Commands
Here are some of the most useful Flask CLI commands:
View Available Commands
To see all available commands:
flask --help
Output:
Usage: flask [OPTIONS] COMMAND [ARGS]...
A general utility script for Flask applications.
Options:
--version Show the flask version
--help Show this message and exit.
Commands:
routes Show the routes for the app.
run Run a development server.
shell Run a shell in the app context.
Viewing Application Routes
To see all defined routes in your application:
flask routes
Output (for a simple app with a few routes):
Endpoint Methods Rule
---------- ------- -----------------------
index GET /
login GET /login
static GET /static/<path:filename>
user GET /user/<username>
Running a Python Shell with Application Context
To start a Python shell with your Flask application context loaded:
flask shell
This is very useful for debugging and testing your app since you can interact with your Flask application objects directly:
>>> from app.models import User
>>> User.query.all()
[<User 'admin'>, <User 'guest'>]
>>> app.url_map
Map([<Rule '/' (HEAD, GET, OPTIONS) -> index>,
<Rule '/static/<filename>' (HEAD, GET, OPTIONS) -> static>,
<Rule '/login' (HEAD, GET, OPTIONS) -> login>])
Creating Custom CLI Commands
You can extend the Flask CLI with your own commands. This is particularly useful for recurring tasks like database initialization, running tests, or deployment-related tasks.
Basic Custom Command
Here's how to add a simple command to your Flask application:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
@app.cli.command('hello')
def hello_command():
"""Say hello with the CLI."""
print('Hello from the Flask CLI!')
You can then run this command with:
flask hello
Output:
Hello from the Flask CLI!
Commands with Arguments
You can also create commands that accept arguments:
# app.py
from flask import Flask
app = Flask(__name__)
@app.cli.command('greet')
@click.argument('name')
def greet_command(name):
"""Greet someone by name."""
print(f'Hello, {name}!')
To use this command:
flask greet Alice
Output:
Hello, Alice!
Commands with Options
Adding options to your commands provides more flexibility:
# app.py
import click
from flask import Flask
app = Flask(__name__)
@app.cli.command('create-user')
@click.option('--username', prompt=True, help='The username of the new user')
@click.option('--admin', is_flag=True, help='Make the user an administrator')
@click.password_option()
def create_user_command(username, admin, password):
"""Create a new user."""
print(f"Creating user: {username}")
print(f"Admin: {'Yes' if admin else 'No'}")
print(f"Password length: {len(password)} characters")
# In a real app, you would add the user to a database here
Using this command:
flask create-user --username john --admin
Output:
Password: (hidden input)
Repeat for confirmation: (hidden input)
Creating user: john
Admin: Yes
Password length: 8 characters
Real-World Examples
Let's look at some practical examples of Flask CLI commands that you might use in real projects.
Database Management Commands
# app.py
import click
from flask import Flask
from flask.cli import with_appcontext
from models import db, User, Post
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db.init_app(app)
@app.cli.command('init-db')
def init_db_command():
"""Initialize the database."""
db.create_all()
click.echo('Initialized the database.')
@app.cli.command('seed-data')
def seed_data_command():
"""Seed the database with sample data."""
# Create a user
user = User(username='admin', email='[email protected]')
user.set_password('password')
db.session.add(user)
# Create some posts
post1 = Post(title='First Post', content='Hello world!', author=user)
post2 = Post(title='Second Post', content='Flask is fun!', author=user)
db.session.add_all([post1, post2])
db.session.commit()
click.echo('Database seeded with sample data.')
@app.cli.command('clear-db')
@click.confirmation_option(prompt='Are you sure you want to drop all tables?')
def clear_db_command():
"""Clear all data in the database."""
db.drop_all()
click.echo('Database cleared.')
Usage and output:
$ flask init-db
Initialized the database.
$ flask seed-data
Database seeded with sample data.
$ flask clear-db
Are you sure you want to drop all tables? [y/N]: y
Database cleared.
Application Deployment Tasks
Here's an example of commands that might be useful during deployment:
# app.py
import os
import click
from flask import Flask
app = Flask(__name__)
@app.cli.command('compile-assets')
def compile_assets_command():
"""Compile and minify CSS and JavaScript assets."""
click.echo('Compiling CSS...')
os.system('sass static/sass:static/css --style compressed')
click.echo('Minifying JavaScript...')
os.system('uglifyjs static/js/source/*.js -o static/js/app.min.js')
click.echo('Assets compiled successfully.')
@app.cli.command('deploy')
@click.option('--environment', '-e', default='production',
type=click.Choice(['development', 'testing', 'production']),
help='The deployment environment')
def deploy_command(environment):
"""Deploy the application to the specified environment."""
click.echo(f'Deploying to {environment} environment...')
# Run different commands based on environment
if environment == 'production':
click.echo('Running production deployment tasks...')
os.system('flask compile-assets')
os.system('alembic upgrade head') # Database migrations
click.echo(f'Application deployed to {environment}.')
Usage and output:
$ flask compile-assets
Compiling CSS...
Minifying JavaScript...
Assets compiled successfully.
$ flask deploy --environment production
Deploying to production environment...
Running production deployment tasks...
Compiling CSS...
Minifying JavaScript...
Assets compiled successfully.
Application deployed to production.
Flask CLI in Flask Extensions
Many Flask extensions add their own commands to the Flask CLI. For example, Flask-Migrate provides commands for handling database migrations:
flask db init # Initialize migrations repository
flask db migrate -m "Initial migration" # Generate a migration
flask db upgrade # Apply migrations
And Flask-Security might add commands for user management:
flask users create # Create a new user
flask roles create # Create a new role
You can explore the commands added by your extensions using flask --help
.
Using Environment Variables with .flaskenv
Rather than setting environment variables each time you run Flask commands, you can use a .flaskenv
file with the python-dotenv package:
pip install python-dotenv
Then create a .flaskenv
file in your project root:
FLASK_APP=app.py
FLASK_ENV=development
FLASK_DEBUG=1
Now Flask will automatically load these variables when you run Flask commands.
Summary
The Flask Command Line Interface is a powerful tool that enhances your development workflow. In this tutorial, we've covered:
- Basic Flask CLI commands like
flask run
andflask routes
- How to enable debug mode for development
- Creating custom commands with arguments and options
- Real-world examples for database management and deployment
- Using Flask extensions with the CLI
- Simplifying your workflow with .flaskenv files
Mastering the Flask CLI will make you more productive and efficient in your Flask development journey. The ability to create custom commands allows you to automate routine tasks and integrate smoothly with your deployment processes.
Additional Resources
- Official Flask CLI Documentation
- Click Documentation - The library Flask uses for its CLI
- Flask Extension Development - For creating CLI commands in extensions
Exercises
- Create a custom Flask CLI command that generates a new Flask blueprint with standard files (views.py, models.py, etc.).
- Implement a CLI command that backs up your database and saves it with a timestamp.
- Create a command that checks your Flask application for common security issues or misconfigurations.
- Build a CLI command that generates test data for your application's models.
- Implement a command that prints statistics about your application's routes (e.g., how many routes use each HTTP method).
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)