0
0
Flaskframework~5 mins

Environment-based configuration in Flask

Choose your learning style9 modes available
Introduction

Environment-based configuration helps your Flask app use different settings for development, testing, and production without changing code.

You want to use a debug mode only when developing.
You need different database connections for testing and production.
You want to keep secret keys safe and not hard-code them.
You want to change app behavior based on where it runs (local or server).
Syntax
Flask
from flask import Flask
import os

app = Flask(__name__)

# Load config from environment variable
app.config.from_envvar('MYAPP_SETTINGS')
Use app.config.from_envvar() to load config from a file path stored in an environment variable.
You can also set config values directly from os.environ.
Examples
Define different config classes for each environment and load the right one.
Flask
import os

class Config:
    DEBUG = False
    SECRET_KEY = 'defaultsecret'

class DevelopmentConfig(Config):
    DEBUG = True
    SECRET_KEY = 'devsecret'

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

app.config.from_object(DevelopmentConfig)
Set a config value directly from an environment variable with a fallback.
Flask
import os

app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'fallbacksecret')
Load configuration from a Python file.
Flask
app.config.from_pyfile('config.py')
Sample Program

This Flask app loads different settings based on the FLASK_ENV environment variable. It shows debug mode and secret key on the homepage.

Flask
from flask import Flask
import os

class Config:
    DEBUG = False
    SECRET_KEY = 'defaultsecret'

class DevelopmentConfig(Config):
    DEBUG = True
    SECRET_KEY = 'devsecret'

class ProductionConfig(Config):
    SECRET_KEY = os.environ.get('SECRET_KEY', 'prodsecret')

app = Flask(__name__)

# Choose config based on environment variable
env = os.environ.get('FLASK_ENV', 'development')
if env == 'production':
    app.config.from_object(ProductionConfig)
else:
    app.config.from_object(DevelopmentConfig)

@app.route('/')
def index():
    debug_mode = app.config['DEBUG']
    secret = app.config['SECRET_KEY']
    return f"Debug: {debug_mode}, Secret: {secret}"

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

Always keep secret keys and sensitive info out of your code and use environment variables.

Use FLASK_ENV or your own variable to switch configs easily.

Remember to restart your app after changing environment variables.

Summary

Use environment-based config to keep your app flexible and secure.

Define separate config classes or files for each environment.

Load config using environment variables and Flask methods like from_object or from_envvar.