How to Use Config in Flask: Simple Guide with Examples
In Flask, you use
app.config to manage configuration settings by assigning key-value pairs or loading from files like .py or .env. You can set configs directly or load them using app.config.from_pyfile() or app.config.from_mapping().Syntax
Flask configuration is stored in app.config, a dictionary-like object. You can set values directly or load from external files.
app.config['KEY'] = 'value': Set a single config key.app.config.from_pyfile('config.py'): Load config from a Python file.app.config.from_mapping({'KEY': 'value'}): Load config from a dictionary.
python
from flask import Flask app = Flask(__name__) # Set config directly app.config['DEBUG'] = True # Load config from a Python file app.config.from_pyfile('config.py') # Load config from a dictionary app.config.from_mapping( SECRET_KEY='mysecret', DATABASE_URI='sqlite:///mydb.sqlite' )
Example
This example shows how to create a Flask app, set configuration values directly, and access them inside a route.
python
from flask import Flask app = Flask(__name__) # Set configuration values app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'supersecretkey' @app.route('/') def home(): debug_mode = app.config['DEBUG'] secret = app.config['SECRET_KEY'] return f"Debug is {debug_mode}, Secret Key is {secret}" if __name__ == '__main__': app.run()
Output
Debug is True, Secret Key is supersecretkey
Common Pitfalls
Common mistakes when using Flask config include:
- Trying to access config keys before setting or loading them, causing
KeyError. - Forgetting to reload or restart the app after changing config files.
- Using incorrect file paths or formats when loading config from files.
- Modifying
app.configafter the app has started without proper context.
python
from flask import Flask app = Flask(__name__) # Wrong: Accessing config before setting it # print(app.config['MY_SETTING']) # KeyError # Right: Set config first app.config['MY_SETTING'] = 'value' print(app.config['MY_SETTING']) # Outputs: value
Output
value
Quick Reference
| Method | Description |
|---|---|
| app.config['KEY'] = value | Set a single configuration key directly |
| app.config.from_pyfile('filename.py') | Load configuration from a Python file |
| app.config.from_mapping(dict) | Load configuration from a dictionary or mapping |
| app.config.from_envvar('ENV_VAR') | Load config from a file path stored in an environment variable |
| app.config.get('KEY', default) | Get a config value with a default fallback |
Key Takeaways
Use app.config to store and access Flask configuration settings as key-value pairs.
Load configuration from files using from_pyfile or from_mapping for better organization.
Always set or load config before accessing keys to avoid errors.
Restart your Flask app after changing config files to apply updates.
Use app.config.get() to safely access config values with defaults.