Working with Blueprint CLI in Flask 3.0

flask 3.0 blueprint cli tutorial
10 November 2024

In the latest version of the Flask framework, namely Flask 3.0, exciting new features have been added. One of these features is the use of Blueprint and CLI, which can greatly simplify a developer's workflow. If you are working with Flask, you must understand the importance of Blueprint in designing and organizing large applications. With the help of this component, we can divide large applications into several smaller, manageable parts, allowing each part to be developed and maintained independently.

However, what is CLI? In the new versions of Flask, it refers to the ability to execute specific commands using the Command Line Interface or CLI added. This capability allows you to execute any command simply without needing to execute them manually each time, effectively performing a series of repetitive tasks with a single straightforward command.

Now assume we want to write a Flask application with several different components and want to create a CLI to manage these components. We should look at an example code to better understand how we can utilize these features.

Example code using Blueprint and CLI in Flask 3.0

from flask import Flask, Blueprint
from flask.cli import with_appcontext
import click

app = Flask(__name__)

bp = Blueprint('my_blueprint', __name__)

@bp.cli.command('print-hello')
@with_appcontext
def print_hello():
"""Print Hello from the CLI."""
click.echo('Hello from the CLI!')

app.register_blueprint(bp)

if __name__ == '__main__':
app.run()

Line by line code explanation

from flask import Flask, Blueprint
In this line, we import the classes Flask and Blueprint from the flask module.

from flask.cli import with_appcontext
This line imports the with_appcontext function from the flask.cli package, which helps us execute a command in the Flask application context.

import click
The click module is used for creating the CLI, and we import it here.

app = Flask(__name__)
We create a new instance of a Flask application.

bp = Blueprint('my_blueprint', __name__)
We create a new Blueprint with the name my_blueprint.

@bp.cli.command('print-hello')
This decorator @bp.cli.command is used to define a new CLI command called print-hello.

@with_appcontext
This decorator ensures that our command runs in the application context.

def print_hello():
This defines the function print_hello.

click.echo('Hello from the CLI!')
This line displays the message Hello from the CLI! in the CLI.

app.register_blueprint(bp)
This line connects the Blueprint to the application.

if __name__ == '__main__':
This line checks if the script is being run as the main program.

app.run()
Runs the Flask application.

FAQ

?

Why should we use Blueprint?

?

What is the use of CLI in Flask?

?

Is Blueprint only available in Flask 3.0?