BudiBadu Logo
Samplebadu

Flask by Example: Application Configuration Modes

Flask 3.0+

Managing configuration across different environments (Development, Testing, Production) is a common challenge. This example shows how to structure your config using Python classes.

Code

from flask import Flask
import os

# 1. Define Config Classes
class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard-to-guess-string'
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite:///:memory:'

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

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

class TestingConfig(Config):
    TESTING = True
    WTF_CSRF_ENABLED = False

# 2. Map names to classes
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}

# 3. Initialize App with Config
def create_app(config_name='default'):
    app = Flask(__name__)
    
    # Load config from the object
    app.config.from_object(config[config_name])
    
    return app

# Usage:
# app = create_app('production')

Explanation

Using Python classes for configuration allows you to leverage inheritance to minimize duplication. You define a base Config class with shared defaults, and then create subclasses like DevelopmentConfig and ProductionConfig to override specific values, such as database URIs or debug flags.

This approach pairs perfectly with the Application Factory pattern. By passing a configuration name (e.g., 'production') to your create_app function, you can dynamically load the correct settings. This makes it easy to spin up your app in different modes without changing the code itself.

Sensitive information like secret keys or database passwords should never be hardcoded in these files. Instead, use os.environ.get() to read them from environment variables. This keeps your secrets safe and allows you to change them easily without redeploying your code.

Code Breakdown

6
os.environ.get('SECRET_KEY') reads from the system environment. The or 'string' provides a fallback for development convenience, but should be avoided in production.
11
class DevelopmentConfig(Config) inherits all settings from Config. It only needs to define what is different, like enabling DEBUG mode.
35
app.config.from_object() loads the configuration. It iterates over all uppercase attributes in the class and adds them to the app.config dictionary.