Flask Configuration Management
Any application needs configuration—database address, secret key, debug mode switch, and so on.
Flask provides a flexible configuration system that supports loading configuration from multiple sources to meet the different needs of development and production.
Config object basics
A Flask application's configuration is stored in app.config, which is like a dict where you can read and write any configuration value by key:
Example
from
flask
import
Flask
app
=
Flask
(
name
)
Set a configuration item directly
app.
config
[
"SECRET_KEY"
]
=
"your-secret-key"
app.
config
[
"DEBUG"
]
=
True
app.
config
[
"DATABASE"
]
=
"runoob.db"
Read configuration
(
app.
config
[
"SECRET_KEY"
]
)
Output: your-secret-key
(
app.
debug
)
Output: True (DEBUG can be accessed via the app.debug attribute)
Configuration key name must be all uppercase, which is Flask's convention, used together with the configuration loading methods.
Built-in configuration items
Flask has many built-in configuration items to control framework behavior; the following are the most commonly used in development:
| Configuration Item | Type | Default value | Description |
|---|---|---|---|
| DEBUG | bool | None | Whether debug mode is enabled (must be False in production) |
| TESTING | bool | False | Whether test mode is enabled |
| SECRET_KEY | str | None | The secret key used to sign sessions (must be set) |
| SERVER_NAME | str | None | Server domain + port, such as "example.com:5000" |
| MAX_CONTENT_LENGTH | int | None | Maximum request body size (in bytes), used to limit uploads |
| SESSION_COOKIE_NAME | str | "session" | The name of the session cookie |
| PERMANENT_SESSION_LIFETIME | timedelta | 31 days | The lifetime of a permanent session |
Loading from a Python file—from_pyfile
The most common practice is to write configuration into a separate Python file and then load it:
# File path: config.py (in the same directory as app.py)
# NOTE: ALL KEY NAMES MUST BE UPPERCASE
SECRET_KEY = "your-production-secret-key"
DATABASE_URL = "postgresql://user:pass@localhost/db"
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 限制上传文件大小 16MB
# Development Configuration
DEBUG = True
app.py code:
# 文件路径:app.py
from flask import Flask
app = Flask(__name__)
# Load all uppercase variables from config.py into app.config
app.config.from_pyfile("config.py")
print(app.config["DATABASE_URL"]) # 输出: postgresql://user:pass@localhost/db
Loading from environment variables—from_prefixed_env
Loading from environment variables is the practice recommended by the 12-Factor App and is best suited for production deployment.
Flask reads environment variables with the FLASK_ prefix by default, and values are attempted to be parsed as JSON types:
# Set environment variables in the terminal (or write to .flaskenv file)
export FLASK_SECRET_KEY="prod-secret"
export FLASK_MAX_CONTENT_LENGTH=16777216
app.py code:
from flask import Flask
from datetime import timedelta
app = Flask(__name__)
# Load default configuration
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=7)
# Automatically load all environment variables starting with FLASK_
# For example, FLASK_SECRET_KEY will become config["SECRET_KEY"]
app.config.from_prefixed_env()
# You can also customize the prefix
# app.config.from_prefixed_env("RUNOOB") # Load variables prefixed with RUNOOB_
Nested configuration
Use a double underscore __ to set nested configuration:
$ export FLASK_DATABASE__HOST="localhost"
$ export FLASK_DATABASE__PORT="5432"
The result after loading:
Example
app.
config
.
from_prefixed_env
(
)
The value of config["DATABASE"] is {"host": "localhost", "port": 5432}
(
app.
config
[
"DATABASE"
]
)
Output: {'host': 'localhost', 'port': 5432}
Loading from JSON/TOML—from_file
Besides Python files and environment variables, Flask also supports loading configuration from formats such as JSON and TOML:
Example
// File path: config.json
{
"SECRET_KEY"
:
"runoob-secret"
,
"DATABASE_URL"
:
"sqlite:///runoob.db"
,
"ITEMS_PER_PAGE"
:
20
}
Example
import
json
app
=
Flask
(
name
)
Load from a JSON file (text=True means text mode, which is True by default)
app.
config
.
from_file
(
"config.json"
,
load
=
json.
load
)
Load from a TOML file (requires tomllib or tomli)
import tomllib
app.config.from_file("config.toml", load=tomllib.load, text=False)
Loading from an object—from_object
Load all uppercase attributes directly from a Python object (a module or class):
Example
Recommended practice: define configuration classes to distinguish environments
class
Config:
SECRET_KEY
=
"dev-key"
DATABASE
=
"dev.db"
class
ProductionConfig
(
Config
)
:
DEBUG
=
False
DATABASE
=
"prod.db"
class
DevelopmentConfig
(
Config
)
:
DEBUG
=
True
Select configuration based on environment variables
import
os
config_mode
=
os
.
environ
.
get
(
"FLASK_CONFIG"
,
"development"
)
if
config_mode
==
"production"
:
app.
config
.
from_object
(
ProductionConfig
)
else
:
app.
config
.
from_object
(
DevelopmentConfig
)
The instance folder—private configuration
Some configurations are not suitable for committing to a code repository (such as production secret keys); these can be placed in the instance folder:
Example
app
=
Flask
(
name
,
instance_relative_config
=
True
)
Load instance/config.py (this file is not committed to Git)
app.
config
.
from_pyfile
(
"config.py"
,
silent
=
True
)
The instance folder is usually located separately outside the project directory
myflaskapp/
├── app.py
├── config.py # 公共配置(可提交到 Git)
└── instance/ # 不提交到 Git(.gitignore)
└── config.py # 私密配置(密钥等)
Configuration loading priority
The most common configuration loading order in practice:
Example
app
=
Flask
(
name
)
1. Load default configuration (hard-coded default values in the code)
app.
config
.
update
(
{
"ITEMS_PER_PAGE"
:
20
,
"MAX_CONTENT_LENGTH"
:
16
1024
1024
,
}
)
2. Load instance configuration (instance/config.py, higher priority than defaults)
app.
config
.
from_pyfile
(
"config.py"
,
silent
=
True
)
3. Load environment variables (highest priority, overrides all previous settings)
app.
config
.
from_prefixed_env
(
)
This priority ensures: defaults are the weakest, file configuration is medium, and environment variables are the strongest—in line with 12-Factor App best practices.