Environment variables help keep sensitive information like passwords safe and let you change settings without changing your code.
0
0
Environment variable management in Flask
Introduction
You want to keep your database password secret and not write it in your code.
You need to switch between development and production settings easily.
You want to share your code without sharing private keys or secrets.
You want to configure your app differently on your computer and on a server.
Syntax
Flask
import os # Get an environment variable value = os.getenv('VARIABLE_NAME', 'default_value')
Use os.getenv to read environment variables safely.
You can provide a default value if the variable is not set.
Examples
This reads the
SECRET_KEY environment variable.Flask
import os secret_key = os.getenv('SECRET_KEY')
This reads the
PORT variable or uses '5000' if not set.Flask
import os port = os.getenv('PORT', '5000')
This reads
DEBUG and converts it to a boolean.Flask
import os debug_mode = os.getenv('DEBUG', 'False') == 'True'
Sample Program
This Flask app reads the SECRET_KEY and PORT from environment variables. It shows the secret key on the home page and runs on the specified port or 5000 by default.
Flask
import os from flask import Flask app = Flask(__name__) # Set secret key from environment variable app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'defaultsecret') @app.route('/') def home(): return f"Secret key is: {app.config['SECRET_KEY']}" if __name__ == '__main__': port = int(os.getenv('PORT', '5000')) app.run(debug=True, port=port)
OutputSuccess
Important Notes
Never commit real secrets to your code repository.
Use a .env file with tools like python-dotenv during development to load environment variables.
Environment variables are strings; convert them if you need other types.
Summary
Environment variables keep sensitive info safe and separate from code.
Use os.getenv to read them with optional defaults.
Set different values for development and production easily.