Flask Config Class API
Config is a dict subclass used to manage all configuration items of a Flask application.
Accessed via app.config, it supports loading configuration from multiple sources.
Config class methods
| Method | Signing | Description |
|---|---|---|
| from_pyfile | (filename, silent=False) | Load configuration from a Python file. When silent=True, ignore the error if the file does not exist |
| from_object | (obj) | Load configuration from an object (module, class, or string import path). Only uppercase attributes are loaded |
| from_envvar | (variable_name, silent=False) | Load configuration from a file pointed to by an environment variable. Equivalent to from_pyfile(os.environ[var]) |
| from_prefixed_env | (prefix="FLASK", *, loads=json.loads) | Load from environment variables. Reads variables with the FLASK_ prefix and sets them as configuration after removing the prefix |
| from_file | (filename, load, silent=False, text=True) | Load from a file in any format. load is the parsing function (such as json.load or tomllib.load) |
| from_mapping | (mapping=None, **kwargs) | Load configuration from a mapping object. Optional **kwargs key-value pairs. Only uppercase keys are loaded |
| get_namespace | (namespace, lowercase=True, trim_namespace=True) | Get a subset of configuration with a specified prefix. For example, get_namespace("DB_") gets all database configuration |
Comparison of loading methods
| Loading method | Applicable scenarios | Example |
|---|---|---|
| from_pyfile | Configuration file in Python format | app.config.from_pyfile("config.py") |
| from_object | Use a class or module to organize configuration and distinguish environments | app.config.from_object("myapp.config.ProductionConfig") |
| from_prefixed_env | 12-Factor App, environment variable configuration | app.config.from_prefixed_env() |
| from_file | Non-Python formats such as JSON and TOML | app.config.from_file("config.json", load=json.load) |
| get_namespace | Extract a configuration subset and pass it to a library's constructor | db_config = app.config.get_namespace("DB_") |
Configuration key naming rules
Configuration key name must be all uppercase. This is Flask's convention; methods such as from_object, from_mapping, and from_prefixed_env automatically ignore lowercase keys.
Code Example
Example
from
flask
import
Flask
app
=
Flask
(
name
)
Method 1: Load from a Python file
app.
config
.
from_pyfile
(
"config.py"
)
Method 2: Load from environment variables (reads the FLASK_ prefix)
app.
config
.
from_prefixed_env
(
)
Method 3: Set directly
app.
config
[
"MY_SETTING"
]
=
"value"
Method 4: Load from JSON
import
json
app.
config
.
from_file
(
"config.json"
,
load
=
json.
load
)
Method 5: Get namespace configuration
Assume there are configurations such as DB_HOST, DB_PORT, and DB_NAME
db_config
=
app.
config
.
get_namespace
(
"DB_"
)