0
0
Flaskframework~5 mins

Command pattern with Flask CLI

Choose your learning style9 modes available
Introduction

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.

You want to run database setup or cleanup tasks from the terminal.
You need to create a command to import or export data.
You want to automate repetitive tasks like sending emails or clearing caches.
You want to add custom commands to your Flask app for easier management.
Syntax
Flask
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.

Examples
A simple command that prints a greeting.
Flask
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)
A command to initialize the database.
Flask
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)
Sample Program

This Flask app adds a CLI command named greet. When you run flask greet in the terminal, it prints a welcome message.

Flask
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()
OutputSuccess
Important Notes

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.

Summary

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.