YouTip LogoYouTip

Flask Config

Any application needs configuration - database address, secret keys, debug mode switch, etc. Flask provides a flexible configuration system that supports loading configuration from multiple sources to meet different development and production needs. * * * ## Config Object Basics The configuration of Flask application is stored in app.config, which works like a dictionary and allows reading/writing any configuration value using key names: ## Example from flask import Flask app = Flask( __name__ ) # Directly set configuration items app.config="your-secret-key" app.config=True app.config="tutorial.db" # Read configuration print(app.config)# Output: your-secret-key print(app.debug)# Output: True (DEBUG can be accessed via app.debug attribute) > Configuration key names must be all uppercase, which is Flask's convention, used together with configuration loading methods. * * * ## Built-in Configuration Options Flask has many built-in configuration options to control framework behavior. Here are the most commonly used in development: | Configuration Option | Type | Default | Description | | --- | --- | --- | --- | | DEBUG | bool | None | Whether to enable debug mode (must be False in production) | | TESTING | bool | False | Whether to enable testing mode | | SECRET_KEY | str | None | Key used for signing Session (required) | | SERVER_NAME | str | None | Server domain name + port, e.g., "example.com:5000" | | MAX_CONTENT_LENGTH | int | None | Maximum request body size (bytes), used to limit uploads | | SESSION_COOKIE_NAME | str | "session" | Name of Session Cookie | | PERMANENT_SESSION_LIFETIME | timedelta | 31 days | Validity period for permanent Session | * * * ## Loading from Python File β€”β€” from_pyfile The most common approach is to write configuration to a separate Python file and then load it: # File path: config.py (same level directory as app.py) # Note: All key names must be uppercase SECRET_KEY = "your-production-secret-key" DATABASE_URL = "postgresql://user:pass@localhost/db" MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # Limit upload file size to 16MB # Development configuration DEBUG = True app.py code: # File path: app.py from flask import Flask app = Flask( __name__ ) # Load all uppercase variables from config.py into app.config app.config.from_pyfile("config.py") print(app.config) # Output: postgresql://user:pass@localhost/db * * * ## Loading from Environment Variables β€”β€” from_prefixed_env Loading from environment variables is the recommended approach for 12-Factor Apps, best suited for production deployment. Flask reads environment variables with the FLASK_ prefix by default, and values will be attempted to be parsed as JSON types: # Set environment variables in terminal (or write to .flaskenv file) 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__ ) # Load default configuration app.config = timedelta(days=7) # Automatically load all environment variables starting with FLASK_ # For example, FLASK_SECRET_KEY becomes config app.config.from_prefixed_env() # You can also customize the prefix # app.config.from_prefixed_env("TUTORIAL") # Load variables with TUTORIAL_ prefix ### Nested Configuration Using double underscores __ allows setting nested configuration: $ export FLASK_DATABASE__HOST="localhost" $ export FLASK_DATABASE__PORT="5432" Result after loading: ## Example app.config.from_prefixed_env() # The value of config is {"host": "localhost", "port": 5432} print(app.config) # Output: {'host': 'localhost', 'port': 5432} * * * ## Loading from JSON/TOML β€”β€” from_file In addition to Python files and environment variables, Flask also supports loading configuration from JSON, TOML and other formats: ## Example // File path: config.json { "SECRET_KEY":"tutorial-secret", "DATABASE_URL":"sqlite:///tutorial.db", "ITEMS_PER_PAGE":20 } ## Example import json app = Flask( __name__ ) # Load from JSON file (text=True means 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) * * * ## Loading from Object β€”β€” from_object Load all
← Flask TestingFlask Static File β†’