Flask Configuration Management

Any application needs configuration—database addresses, keys, debug mode switches, and so on.

Flask provides a flexible configuration system that supports loading configuration from multiple sources to meet different needs in development and production.


Config Object Basics

Flask application configuration is stored inapp.configIn it, it is like a dictionary, and you can read and write any configuration value by key name:

Example

from flask import Flask

app = Flask(__name__)

# Directly set configuration items
app.config["SECRET_KEY"] = "your-secret-key"
app.config["DEBUG"] = True
app.config["DATABASE"] = "example.db"

# Read configuration
print(app.config["SECRET_KEY"])  # Output: your-secret-key
print(app.debug)                 # Output: True (DEBUG can be accessed via the app.debug attribute)

Configuration Key NamesMust be entirely uppercaseThis is a Flask convention, used together with configuration loading methods.


Built-in Configuration Items

Flask has a large number of 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 to enable debug mode (must be False in production)
TESTING bool False Whether to enable test mode
SECRET_KEY str None The secret key used for signing Session (must be set)
SERVER_NAME str None Server domain + port, e.g. "example.com:5000"
MAX_CONTENT_LENGTH int None Maximum request body size (in bytes), used to limit uploads
SESSION_COOKIE_NAME str "session" Session Cookie Name
PERMANENT_SESSION_LIFETIME timedelta 31 days Validity period of permanent Session

Load from Python file — from_pyfile

The most common practice is to write the configuration into a separate Python file and then load it:

# 文件路径:config.py(与 app.py 同级目录)
# 注意:所有键名必须大写
SECRET_KEY = "your-production-secret-key"
DATABASE_URL = "postgresql://user:pass@localhost/db"
MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 限制上传文件大小 16MB

# 开发配置
DEBUG = True

app.py code:

# 文件路径:app.py
from flask import Flask

app = Flask(__name__)

# 加载 config.py 中所有大写的变量到 app.config
app.config.from_pyfile("config.py")

print(app.config["DATABASE_URL"])  # 输出: postgresql://user:pass@localhost/db

Load from environment variables——from_prefixed_env

Loading from environment variables is a recommended practice of the 12-Factor App, best suited for production deployment.

Flask reads by defaultFLASK_Environment variables with the prefix, and the values will be attempted to be parsed as JSON type:

# 在终端设置环境变量(或写入 .flaskenv 文件)
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__)

# 加载默认配置
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=7)

# 自动加载所有以 FLASK_ 开头的环境变量
# 例如 FLASK_SECRET_KEY 会成为 config["SECRET_KEY"]
app.config.from_prefixed_env()

# 也可以自定义前缀
# app.config.from_prefixed_env("EXAMPLE")  # 加载 EXAMPLE_ 前缀的变量

Nested configuration

Using double underscores__Nested configuration can be set:

$ export FLASK_DATABASE__HOST="localhost"
$ export FLASK_DATABASE__PORT="5432"

Result after loading:

Example

app.config.from_prefixed_env()
# The value of config["DATABASE"] is {"host": "localhost", "port": 5432}
print(app.config["DATABASE"])  # Output: {'host': 'localhost', 'port': 5432}

Load 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": "example-secret",
  "DATABASE_URL": "sqlite:///example.db",
  "ITEMS_PER_PAGE": 20
}

Example

import json

app = Flask(__name__)

# Load from JSON file (text=True indicates text mode, default is True)
app.config.from_file("config.json", load=json.load)
# Load from TOML file (requires tomllib or tomli)
# import tomllib
# app.config.from_file("config.toml", load=tomllib.load, text=False)

Load from object——from_object

Load all uppercase attributes directly from a Python object (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). They can be placed ininstanceIn the 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 in a separate location outside the project directory
myflaskapp/
├── app.py
├── config.py         # 公共配置(可提交到 Git)
└── instance/          # 不提交到 Git(.gitignore)
    └── config.py     # 私密配置(密钥等)

Configuration loading priority

A common configuration loading order in practice:

Example

app = Flask(__name__)

# 1. Load default configuration (hardcoded default values in 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()

Such priority ensures: default values are the weakest, file configuration is medium, and environment variables are the strongest—conforming to the 12-Factor App best practices.

other extensions