Object and Mapping Configuration
Flask manages application settings through the Config class, which is a specialized dictionary. A defining characteristic of Flask's configuration system is the uppercase rule: only keys consisting entirely of uppercase letters are accepted as configuration. This allows you to define temporary variables or helper functions within your configuration files or objects without them being accidentally imported into the application's configuration.
Mapping Configuration
When you need to set initial defaults or merge configuration from a dictionary, use from_mapping. This is particularly common in application factories where you want to ensure certain keys exist before loading external files.
In the Flask tutorial, from_mapping is used to establish a default SECRET_KEY and database path:
# examples/tutorial/flaskr/__init__.py
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY="dev",
DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"),
)
Internally, from_mapping iterates over the provided mapping and keyword arguments, applying the uppercase filter before updating the Config instance:
# src/flask/config.py
for key, value in mappings.items():
if key.isupper():
self[key] = value
Object and Module Configuration
For more structured configuration, from_object allows you to load settings from Python modules or classes. This is useful for maintaining different configuration profiles (e.g., DevelopmentConfig, ProductionConfig) as classes.
Loading from a Class
You can pass a class reference directly to from_object. Flask will inspect the class and pull out all uppercase attributes.
class Config:
SECRET_KEY = "default-key"
DEBUG = False
class ProductionConfig(Config):
DATABASE_URI = "mysql://user@localhost/foo"
app.config.from_object(ProductionConfig)
Loading from a Module
You can also pass an import string. Flask uses werkzeug.utils.import_string to resolve the name and then treats the resulting module as the source object.
app.config.from_object("yourapplication.default_config")
Internal Mechanism and Constraints
The from_object method uses dir(obj) to find attributes. Because it looks for attributes rather than dictionary keys, you cannot pass a dictionary to from_object; use from_mapping for dictionaries instead.
If you use a class with @property attributes, you must instantiate the class before passing it to from_object, as the method does not trigger property descriptors on uninstantiated classes.
# src/flask/config.py
def from_object(self, obj: object | str) -> None:
if isinstance(obj, str):
obj = import_string(obj)
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)
Environment Variable Configuration
For containerized or Twelve-Factor applications, from_prefixed_env provides a way to load configuration directly from the environment. By default, it looks for variables starting with FLASK_.
Type Conversion and Nesting
Unlike standard environment variables which are always strings, from_prefixed_env attempts to parse values using json.loads. This allows you to set booleans, integers, or even lists and dictionaries from the environment.
If you need to populate a nested dictionary in your config, use a double underscore (__) as a separator in the environment variable name.
# Environment:
# FLASK_DEBUG=true
# FLASK_DATABASE__HOST="localhost"
# FLASK_DATABASE__PORT=5432
app.config.from_prefixed_env()
# Resulting config:
# app.config["DEBUG"] is True
# app.config["DATABASE"] == {"HOST": "localhost", "PORT": 5432}
The implementation in flask.config handles the prefix stripping and the recursive dictionary creation:
# src/flask/config.py
for key in sorted(os.environ):
if not key.startswith(prefix):
continue
value = os.environ[key]
key = key.removeprefix(prefix)
try:
value = loads(value)
except Exception:
pass # Keep as string if JSON loading fails
# ... logic to handle "__" for nested dicts ...
Extracting Configuration Subsets
If you are integrating with a library that expects its own configuration dictionary, get_namespace can extract a subset of settings based on a prefix. It can also strip the prefix and lowercase the keys to match standard Python keyword arguments.
app.config["IMAGE_STORE_TYPE"] = "fs"
app.config["IMAGE_STORE_PATH"] = "/var/app/images"
# Extract settings for the image store
image_config = app.config.get_namespace("IMAGE_STORE_")
# image_config is {'type': 'fs', 'path': '/var/app/images'}
This is implemented by iterating over the Config items and filtering by the namespace string:
# src/flask/config.py
for k, v in self.items():
if not k.startswith(namespace):
continue
if trim_namespace:
key = k[len(namespace) :]
# ... handle lowercasing ...
rv[key] = v