The Development Server and CLI
This tutorial guides you through using the built-in development server and the Command Line Interface (CLI) provided by the Flask application. You will learn how to serve your application locally, enable debugging features, and extend the flask command with your own custom logic.
By the end of this guide, you will have a working development environment and a custom CLI command that interacts with your application.
Prerequisites
To follow this tutorial, you need:
- Python installed on your system.
- The
flaskpackage installed in your environment. - A basic understanding of environment variables.
Step 1: Create a Basic Application
First, create a file named hello.py to serve as your application entry point.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, Flask!"
In this step, you initialize the Flask class. The import_name (passed as __name__) helps the application locate resources like templates and static files relative to this module.
Step 2: Start the Development Server via CLI
The recommended way to run your application during development is using the flask run command. This command uses the FlaskGroup CLI tool to discover and serve your app.
Open your terminal and run:
export FLASK_APP=hello
flask run
On Windows (Command Prompt): set FLASK_APP=hello
On Windows (PowerShell): $env:FLASK_APP = "hello"
What happens here:
FLASK_APPtells the CLI which module to load. Thelocate_appfunction insrc/flask/cli.pysearches for anapporapplicationinstance in that module.- The server starts on the default host
127.0.0.1and port5000. - You can now visit
http://127.0.0.1:5000in your browser to see "Hello, Flask!".
Step 3: Enable Debug Mode
Debug mode provides two critical features for development: an interactive debugger and an automatic reloader that restarts the server when you change your code.
Enable it by setting the FLASK_DEBUG environment variable:
export FLASK_DEBUG=1
flask run
Verifying the result:
- Reloader: Change the return string in
hello.pyto "Hello, Debugger!" and save. The terminal will show* Detected change in 'hello.py', reloading. - Debugger: If an error occurs, Flask will display an interactive traceback in the browser.
The Flask.run method and the CLI both check get_debug_flag() to determine if these features should be enabled.
Step 4: Use the Script-Based Entry Point
While the CLI is preferred, you can also start the server directly from your Python script using the run() method. This is useful for quick testing or when using an IDE's "Run" button.
Update hello.py:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, Script!"
if __name__ == "__main__":
app.run(debug=True)
Now you can run the script directly:
python hello.py
Important Note on the Guard:
The if __name__ == "__main__": guard is critical. As seen in src/flask/app.py, the run() method checks the FLASK_RUN_FROM_CLI environment variable. If you try to call app.run() while the app is being imported by the flask CLI, Flask will ignore the call and print a warning to prevent blocking the CLI command.
Step 5: Create a Custom CLI Command
The Flask object includes a cli attribute, which is an instance of AppGroup. You can use this to register custom commands that automatically run within the application context.
Add this to hello.py:
import click
from flask import current_app
@app.cli.command("hello-app")
@click.argument("name")
def hello_app_command(name):
"""Print the app name and a greeting."""
click.echo(f"App: {current_app.name}, Hello {name}!")
Run your custom command:
export FLASK_APP=hello
flask hello-app "Developer"
How it works:
app.cli.command()registers the function with the application's command group.- Because
AppGroup(defined insrc/flask/cli.py) automatically wraps commands inwith_appcontext, you can safely usecurrent_appinside your command to access application configuration or state.
Complete Result
Your hello.py file should now look like this:
import click
from flask import Flask, current_app
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, World!"
@app.cli.command("hello-app")
@click.argument("name")
def hello_app_command(name):
"""Print the app name and a greeting."""
click.echo(f"App: {current_app.name}, Hello {name}!")
if __name__ == "__main__":
# This allows running via 'python hello.py'
app.run(debug=True)
Next Steps
- Explore Environment Variables: Use a
.flaskenvfile to storeFLASK_APPandFLASK_DEBUGso you don't have to export them every session. - Production Deployment: Remember that
app.run()andflask runuse the Werkzeug development server. For production, you should use a WSGI server like Gunicorn or uWSGI. - CLI Groups: Use
app.cli.group()to organize related commands into sub-commands.