0
0
Flaskframework~30 mins

Command pattern with Flask CLI - Mini Project: Build & Apply

Choose your learning style9 modes available
Command pattern with Flask CLI
📖 Scenario: You are building a Flask web application that needs custom command-line commands to manage tasks like database setup and data seeding.Using Flask's CLI system, you will create commands that follow the command pattern, making your app easier to manage and extend.
🎯 Goal: Create a Flask CLI command using the command pattern that prints a welcome message.This will help you understand how to add custom commands to your Flask app.
📋 What You'll Learn
Create a Flask app instance
Define a command class following the command pattern
Register the command with Flask CLI
Run the command to print a message
💡 Why This Matters
🌍 Real World
Custom CLI commands help automate tasks like database setup, data import, or maintenance in Flask web apps.
💼 Career
Knowing how to add and organize CLI commands is valuable for backend developers working with Flask to improve app management and deployment.
Progress0 / 4 steps
1
Create the Flask app instance
Create a Flask app instance called app using Flask(__name__).
Flask
Need a hint?

Use app = Flask(__name__) to create the app instance.

2
Define a command class following the command pattern
Define a class called WelcomeCommand with a method run that prints the string "Welcome to Flask CLI!".
Flask
Need a hint?

Create a class with a run method that prints the welcome message.

3
Register the command with Flask CLI
Import with_appcontext from flask.cli. Then, create a function welcome that creates an instance of WelcomeCommand and calls its run method. Decorate this function with @app.cli.command("welcome") and @with_appcontext.
Flask
Need a hint?

Use decorators @app.cli.command("welcome") and @with_appcontext on the function that runs the command.

4
Complete the Flask CLI command setup
Add the if __name__ == '__main__': block and call app.run() inside it to complete the Flask app setup.
Flask
Need a hint?

Add the standard Python main block to run the Flask app.