Skip to main content

Config

The Config class works exactly like a dict but provides ways to fill it from files or special dictionaries.

Constructor

Config(
    root_path: str | os.PathLike[str],
    defaults: dict[str, Any] | None = None
)
root_path
str | os.PathLike[str]
required
Path to which files are read relative from. When the config object is created by the application, this is the application’s root_path.
defaults
dict[str, Any] | None
default:"None"
An optional dictionary of default values.

Example

from flask import Flask

app = Flask(__name__)
app.config['DEBUG'] = True

Loading Configuration

from_pyfile()

Updates the values in the config from a Python file.
config.from_pyfile(
    filename: str | os.PathLike[str],
    silent: bool = False
) -> bool
filename
str | os.PathLike[str]
required
The filename of the config. This can either be an absolute filename or a filename relative to the root path.
silent
bool
default:"False"
Set to True if you want silent failure for missing files.
Returns True if the file was loaded successfully.

Example

app.config.from_pyfile('config.py')
config.py:
DEBUG = True
SECRET_KEY = 'dev-secret-key'
DATABASE_URI = 'sqlite:///app.db'

from_object()

Updates the values from the given object.
config.from_object(obj: object | str) -> None
obj
object | str
required
An import name or object. If it’s a string, the object with that name will be imported.
Loads only the uppercase attributes of the module/class.

Example

# From module
app.config.from_object('config.default')

# From class
class Config:
    DEBUG = False
    TESTING = False
    SECRET_KEY = 'secret'

class DevelopmentConfig(Config):
    DEBUG = True

app.config.from_object(DevelopmentConfig())

from_envvar()

Loads a configuration from an environment variable pointing to a configuration file.
config.from_envvar(
    variable_name: str,
    silent: bool = False
) -> bool
variable_name
str
required
Name of the environment variable.
silent
bool
default:"False"
Set to True if you want silent failure for missing files.
Returns True if the file was loaded successfully.

Example

export MYAPP_SETTINGS='/path/to/config.py'
app.config.from_envvar('MYAPP_SETTINGS')

from_file()

Update the values in the config from a file that is loaded using the load parameter.
config.from_file(
    filename: str | os.PathLike[str],
    load: Callable[[IO], Mapping],
    silent: bool = False,
    text: bool = True
) -> bool
filename
str | os.PathLike[str]
required
The path to the data file. This can be an absolute path or relative to the config root path.
load
Callable[[IO], Mapping]
required
A callable that takes a file handle and returns a mapping of loaded data from the file.
silent
bool
default:"False"
Ignore the file if it doesn’t exist.
text
bool
default:"True"
Open the file in text or binary mode.
Returns True if the file was loaded successfully.

Example

import json
app.config.from_file('config.json', load=json.load)
import tomllib
app.config.from_file('config.toml', load=tomllib.load, text=False)

from_mapping()

Updates the config like update() ignoring items with non-upper keys.
config.from_mapping(
    mapping: Mapping[str, Any] | None = None,
    **kwargs: Any
) -> bool
mapping
Mapping[str, Any] | None
default:"None"
A mapping object to load config values from.
**kwargs
Additional keyword arguments to load as config values.
Always returns True.

Example

app.config.from_mapping(
    DEBUG=True,
    SECRET_KEY='dev'
)

app.config.from_mapping({
    'DEBUG': True,
    'SECRET_KEY': 'dev'
})

from_prefixed_env()

Load any environment variables that start with FLASK_, dropping the prefix from the env key for the config key.
config.from_prefixed_env(
    prefix: str = "FLASK",
    *,
    loads: Callable[[str], Any] = json.loads
) -> bool
prefix
str
default:"'FLASK'"
Load env vars that start with this prefix, separated with an underscore (_).
loads
Callable[[str], Any]
default:"json.loads"
Pass each string value to this function and use the returned value as the config value. If any error is raised it is ignored and the value remains a string.
Keys are loaded in sorted order. The default loading function attempts to parse values as any valid JSON type, including dicts and lists. Specific items in nested dicts can be set by separating the keys with double underscores (__). Returns True.

Example

export FLASK_SECRET_KEY='my-secret'
export FLASK_DEBUG=true
export FLASK_DATABASE__HOST='localhost'
export FLASK_DATABASE__PORT=5432
app.config.from_prefixed_env()

# Results in:
# SECRET_KEY = 'my-secret'
# DEBUG = True
# DATABASE = {'HOST': 'localhost', 'PORT': 5432}

Accessing Configuration

get_namespace()

Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix.
config.get_namespace(
    namespace: str,
    lowercase: bool = True,
    trim_namespace: bool = True
) -> dict[str, Any]
namespace
str
required
A configuration namespace (prefix).
lowercase
bool
default:"True"
A flag indicating if the keys of the resulting dictionary should be lowercase.
trim_namespace
bool
default:"True"
A flag indicating if the keys of the resulting dictionary should not include the namespace.
Returns a dictionary with the matching configuration values.

Example

app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'

image_store_config = app.config.get_namespace('IMAGE_STORE_')
# Returns:
# {
#     'type': 'fs',
#     'path': '/var/app/images',
#     'base_url': 'http://img.website.com'
# }

Configuration Best Practices

Development vs Production

# config.py
class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///dev.db'

class ProductionConfig(Config):
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')

config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
}
# app.py
from flask import Flask
from config import config

app = Flask(__name__)
config_name = os.environ.get('FLASK_ENV', 'default')
app.config.from_object(config[config_name])

Instance Folder Configuration

app = Flask(__name__, instance_relative_config=True)

# Load default config
app.config.from_object('config.default')

# Load instance config (not in version control)
app.config.from_pyfile('config.py', silent=True)

Environment Variables

import os

app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['DATABASE_URI'] = os.environ.get('DATABASE_URI')

# Or use from_prefixed_env
app.config.from_prefixed_env()

Common Configuration Keys

KeyDescriptionDefault
DEBUGEnable debug modeFalse
TESTINGEnable testing modeFalse
SECRET_KEYSecret key for sessionsNone
SESSION_COOKIE_NAMEName of the session cookie'session'
SESSION_COOKIE_HTTPONLYHttpOnly flag for session cookieTrue
SESSION_COOKIE_SECURESecure flag for session cookieFalse
PERMANENT_SESSION_LIFETIMESession lifetime as timedeltatimedelta(days=31)
MAX_CONTENT_LENGTHMaximum request content lengthNone
SEND_FILE_MAX_AGE_DEFAULTMax age for send_file cacheNone
TRAP_HTTP_EXCEPTIONSTrap HTTP exceptionsFalse
TEMPLATES_AUTO_RELOADAuto-reload templatesNone (based on DEBUG)
PREFERRED_URL_SCHEMEURL scheme for url_for'http'
SERVER_NAMEServer name and portNone
APPLICATION_ROOTApplication root path'/'

Build docs developers (and LLMs) love