The command pattern helps organize tasks you want to run from the command line in a clear way. Flask CLI lets you add these commands easily to your Flask app.
Command pattern with Flask CLI
from flask.cli import with_appcontext import click @click.command() @with_appcontext def my_command(): # Your task code here click.echo('Task done!') app.cli.add_command(my_command)
@click.command() defines a new CLI command.
@with_appcontext ensures the command runs with Flask app context.
import click from flask.cli import with_appcontext @click.command() @with_appcontext def hello(): click.echo('Hello from Flask CLI!') app.cli.add_command(hello)
import click from flask.cli import with_appcontext @click.command() @with_appcontext def init_db(): # Imagine code here to initialize the database click.echo('Database initialized!') app.cli.add_command(init_db)
This Flask app adds a CLI command named greet. When you run flask greet in the terminal, it prints a welcome message.
from flask import Flask import click from flask.cli import with_appcontext app = Flask(__name__) @click.command() @with_appcontext def greet(): """Prints a greeting message.""" click.echo('Hello, welcome to Flask CLI!') app.cli.add_command(greet) if __name__ == '__main__': app.run()
Make sure to set the FLASK_APP environment variable to your app file before running commands.
You can add multiple commands by defining more functions with @click.command() and adding them with app.cli.add_command().
Use click.echo() instead of print() for better CLI output handling.
The command pattern organizes CLI tasks as separate commands.
Flask CLI uses click decorators to create commands easily.
Commands run with app context to access Flask features.
Practice
Solution
Step 1: Understand the command pattern concept
The command pattern helps organize code by encapsulating tasks as commands that can be run independently.Step 2: Relate to Flask CLI usage
Flask CLI uses this pattern to let developers define separate commands for different tasks, making CLI management easier.Final Answer:
To organize CLI tasks as separate, reusable commands -> Option BQuick Check:
Command pattern = organize CLI tasks [OK]
- Confusing CLI commands with web routes
- Thinking commands auto-generate HTML
- Assuming commands only handle databases
Solution
Step 1: Identify Flask CLI command decorator
Flask CLI uses the@app.cli.commanddecorator to register custom CLI commands.Step 2: Differentiate from other decorators
@app.route is for web routes, @click.command is from click but not directly used on Flask app, and @flask.cli.command is incorrect syntax.Final Answer:
@app.cli.command -> Option AQuick Check:
Flask CLI command decorator = @app.cli.command [OK]
- Using @app.route for CLI commands
- Confusing @click.command with Flask app decorator
- Typing @flask.cli.command which is invalid
flask greet?
import click
from flask import Flask
app = Flask(__name__)
@app.cli.command()
@click.argument('name')
def greet(name):
click.echo(f'Hello, {name}!')Solution
Step 1: Analyze the command definition
The commandgreetrequires a positional argumentnamedue to@click.argument('name').Step 2: Check the command usage
Runningflask greetwithout providingnamewill cause Click to raise an error about the missing argument.Final Answer:
Error: Missing argument 'name' -> Option DQuick Check:
Missing required argument causes error [OK]
- Assuming default values for arguments
- Expecting 'name' to print literally
- Ignoring Click argument requirements
from flask import Flask
app = Flask(__name__)
@app.cli.command()
def hello():
print('Hello from CLI')
if __name__ == '__main__':
app.run()Solution
Step 1: Review the purpose of app.run()
app.run()starts the Flask web server and is not needed or appropriate in CLI command files.Step 2: Understand CLI command usage
Flask CLI commands run viaflaskcommand, so runningapp.run()here will start the server unnecessarily and block CLI commands.Final Answer:
Running app.run() in CLI command file -> Option CQuick Check:
app.run() should not be in CLI command files [OK]
- Thinking print is wrong (it's allowed but click.echo preferred)
- Assuming @click.argument is always required
- Not separating web server run from CLI commands
Solution
Step 1: Understand Flask CLI command with app context
Commands need Flask app context to access database and app features, so usewith app.app_context()inside the command function.Step 2: Evaluate options
@app.route is for web routes, not CLI commands. Calling functions without decorators won't register CLI commands. Using @click.command alone lacks app context, causing errors.Final Answer:
Use @app.cli.command and inside the function, query users within a with app.app_context() block -> Option AQuick Check:
CLI commands need app context for DB access [OK]
- Using @app.route for CLI commands
- Forgetting app context for DB access
- Not registering commands with decorators
Ready to prove it?
Pass the test and this pattern moves unknown
