In this tutorial, we will cover how to use the Flask Command Line Interface (CLI) for managing your Flask application. The Flask CLI provides a series of commands for handling various tasks related to Flask projects.
By the end of this tutorial, you will learn how to:
- Initialize a Flask application using CLI
- Run the development server using CLI
- Use different Flask CLI commands for application management
Prerequisites:
- Basic Python programming knowledge
- Basic Flask framework knowledge
- Python and Flask installed on your system
The Flask CLI is a powerful tool that can help you manage your Flask applications. It enables you to initialize and run your application, manage databases, and perform other tasks.
To use Flask CLI, you will first need to set the FLASK_APP environment variable to your application. You can do this using the export
command on Unix/Mac or set
on Windows:
export FLASK_APP=hello.py # Unix/Mac
set FLASK_APP=hello.py # Windows
Here, hello.py
is the file containing your Flask application.
You can now run your application using the flask run
command:
flask run
This command starts a development server that you can use for testing your application.
Let's look at some practical examples of using Flask CLI.
Example 1: Initializing and running a Flask application
# hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
In the terminal, set the FLASK_APP environment variable and run the server:
export FLASK_APP=hello.py
flask run
You should now be able to access your application at http://127.0.0.1:5000.
Example 2: Using Flask CLI to manage database migrations
Flask CLI can be used with Flask-Migrate to handle database migrations. Here is an example:
# hello.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
In the terminal, initialize Flask-Migrate and perform a migration:
export FLASK_APP=hello.py
flask db init
flask db migrate -m "users table"
flask db upgrade
In this tutorial, we learned how to use the Flask CLI to manage our Flask applications. We covered how to initialize and run an application, and we also discussed how to use Flask CLI for database migrations.
For further learning, explore the Flask CLI documentation.
Exercise 1: Create a basic Flask application and run it using Flask CLI.
Exercise 2: Add a new route to your application and test it.
Exercise 3: Use Flask CLI and Flask-Migrate to create a new table in your application's database.
Solutions and explanations will be provided, but try to solve these exercises on your own first. This will help you gain a deeper understanding of the concepts.