Flask CLI & Environment Configuration
Flask CLI & Environment Configuration
While running python app.py works for simple one-file experiments, professional Flask development relies on the Flask Command Line Interface (CLI) and robust environment configuration.
1. The flask CLI Command
Flask includes a built-in CLI powered by the click library. The primary command is flask run.
When you execute flask run, Flask searches for an application entry point in the current working directory following this resolution order:
- 1The file or module specified by the
FLASK_APPenvironment variable. - 2
wsgi.py - 3
app.py
2. Configuring Environment Variables
In modern web development, configuration must be separated from source code (as mandated by The Twelve-Factor App methodology). We configure Flask using environment variables:
| Variable | Values | Purpose |
|---|---|---|
FLASK_APP | app.py, src.app, myapp:create_app() | Points to the entry point module or factory function |
FLASK_DEBUG | 1 (true), 0 (false) | Enables/disables live code reloader and interactive debugger |
SECRET_KEY | Hex string / random secret | Cryptographic key used to sign session cookies and CSRF tokens |
DATABASE_URL | Connection string | Database URI for SQLite, PostgreSQL, or MySQL |
3. Automated Configuration with python-dotenv
Manually setting environment variables in every new terminal session is error-prone. Flask natively integrates with python-dotenv:
When python-dotenv is installed, the flask CLI automatically detects and loads environment variables from two files in your project root:
- 1
.env: Sensitive variables (passwords, API keys, secrets) — never committed to Git. - 2
.flaskenv: Public, project-wide development settings — committed to Git.
Example .flaskenv:
Example .env:
4. Structured Configuration Classes in Flask
Instead of scattering os.environ.get() calls throughout your code, create a centralized config.py file using Python classes:
Loading the configuration into your Flask app:
Practice Quiz
.env and .flaskenv files when executing flask run?.flaskenv and .env?FLASK_APP is not set, which file names will Flask automatically inspect by default?Dynamic URLs & Type Converters
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Virtual Environments & First Flask Application | Dynamic URLs & Type Converters |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.