0
0
Flaskframework~5 mins

Configuration management in Flask

Choose your learning style9 modes available
Introduction

Configuration management helps you keep your app settings organized and easy to change without touching the main code.

You want to set different settings for development and production.
You need to keep secret keys or passwords safe and separate from code.
You want to change database connection details without rewriting your app.
You want to enable or disable features easily by changing config values.
You want to keep your app flexible and easy to maintain.
Syntax
Flask
app = Flask(__name__)
app.config['KEY'] = 'value'

# Or load from a config file
app.config.from_pyfile('config.py')

You can set config values directly on app.config like a dictionary.

Using from_pyfile loads settings from a separate Python file.

Examples
Set debug mode on directly in your app.
Flask
app.config['DEBUG'] = True
Load all config values from a separate file named config.py.
Flask
app.config.from_pyfile('config.py')
Set multiple config values at once using from_mapping.
Flask
app.config.from_mapping(
    SECRET_KEY='mysecret',
    DATABASE_URI='sqlite:///mydb.sqlite'
)
Sample Program

This simple Flask app sets configuration values directly. It shows how to read those values inside a route to change behavior or display info.

Flask
from flask import Flask

app = Flask(__name__)

# Set config directly
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'supersecretkey'

@app.route('/')
def home():
    debug_status = 'on' if app.config['DEBUG'] else 'off'
    return f"Debug mode is {debug_status}. Secret key length is {len(app.config['SECRET_KEY'])}."

if __name__ == '__main__':
    app.run()
OutputSuccess
Important Notes

Keep secret keys out of public code by using environment variables or separate config files.

You can create different config files for development, testing, and production.

Use app.config.from_envvar() to load config from environment variable paths.

Summary

Configuration management keeps your app settings organized and easy to change.

Use app.config like a dictionary to set or get settings.

Load settings from files or environment variables for flexibility and security.