Configuration management helps you keep your app settings organized and easy to change without touching the main code.
Configuration management in 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.
app.config['DEBUG'] = True
config.py.app.config.from_pyfile('config.py')from_mapping.app.config.from_mapping(
SECRET_KEY='mysecret',
DATABASE_URI='sqlite:///mydb.sqlite'
)This simple Flask app sets configuration values directly. It shows how to read those values inside a route to change behavior or display info.
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()
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.
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.
Practice
app.config in a Flask application?Solution
Step 1: Understand the role of
app.configapp.configis a special dictionary in Flask used to keep app settings organized.Step 2: Compare with other Flask features
User sessions, URL routes, and templates are handled by other parts of Flask, notapp.config.Final Answer:
To store and manage application settings -> Option DQuick Check:
App settings = app.config [OK]
- Confusing config with routing or templates
- Thinking config handles user data
- Assuming config runs code
DEBUG to True in Flask?Solution
Step 1: Recall Flask config syntax
Flask config uses dictionary syntax:app.config['KEY'] = value.Step 2: Check each option
app.config['DEBUG'] = True uses correct dictionary syntax. Dot notation, set_config, and config.set use invalid or non-existent methods.Final Answer:
app.config['DEBUG'] = True -> Option AQuick Check:
Set config like dict key-value [OK]
- Using dot notation instead of dictionary syntax
- Calling non-existent methods like set_config
- Confusing config with other Flask methods
app = Flask(__name__)
app.config['DEBUG'] = False
app.config.from_mapping({'DEBUG': True, 'TESTING': True})
print(app.config['DEBUG'])What will be printed?
Solution
Step 1: Understand config assignment order
First,DEBUGis set toFalse. Thenfrom_mappingupdates it toTrue.Step 2: Determine final value
The last assignment wins, soDEBUGbecomesTrue.Final Answer:
True -> Option BQuick Check:
Last config set wins [OK]
- Assuming first value stays
- Thinking from_mapping adds without overwrite
- Expecting error on duplicate keys
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.config['SECRET_KEY'] = 'mysecret'Assuming
config.py does not exist in the project folder.Solution
Step 1: Understand from_pyfile behavior
from_pyfiletries to load a Python file and raises an error if missing.Step 2: Check file existence
Sinceconfig.pydoes not exist, aFileNotFoundErroroccurs immediately.Final Answer:
It will raise a FileNotFoundError -> Option AQuick Check:
Missing config file causes error [OK]
- Thinking Flask ignores missing config files
- Assuming config keys set before loading file are overwritten
- Expecting None values on missing keys
Solution
Step 1: Understand environment variable access
os.getenv('KEY', default)returns the environment value or default if missing.Step 2: Analyze each option
app.config['DEBUG'] = os.getenv('DEBUG', False) usesos.getenvwith defaultFalse, correctly providing fallback. app.config['DEBUG'] = os.environ['DEBUG'] or False may raise KeyError if 'DEBUG' missing. app.config['DEBUG'] = os.environ.get('DEBUG') returns None if missing but no default. app.config['DEBUG'] = os.getenv('DEBUG') or None returns None if missing, not False.Final Answer:
app.config['DEBUG'] = os.getenv('DEBUG', False) -> Option CQuick Check:
Use getenv with default for safe config [OK]
- Using os.environ[] without checking existence
- Not providing default values
- Confusing os.environ.get with os.getenv
Ready to prove it?
Pass the test and this pattern moves unknown
