How to Use Environment Variables in Flask for Configuration
In Flask, you can access environment variables using the
os.environ dictionary from Python's os module. This lets you keep sensitive data like API keys or configuration settings outside your code by setting them in your system or .env files and reading them in your Flask app.Syntax
To use environment variables in Flask, first import the os module. Then access variables with os.environ.get('VARIABLE_NAME'). This returns the value of the environment variable or None if it is not set.
You can also provide a default value like os.environ.get('VARIABLE_NAME', 'default_value') to avoid errors if the variable is missing.
python
import os secret_key = os.environ.get('SECRET_KEY', 'defaultsecret') print(secret_key)
Output
defaultsecret
Example
This example shows a simple Flask app that reads a secret key from an environment variable to configure the app securely. If the variable is not set, it uses a fallback value.
python
import os from flask import Flask app = Flask(__name__) # Get secret key from environment variable app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'fallbacksecret') @app.route('/') def home(): return f"Secret key is: {app.config['SECRET_KEY']}" if __name__ == '__main__': app.run(debug=True)
Output
Secret key is: fallbacksecret
Common Pitfalls
- Not setting environment variables: If you forget to set them, your app may use insecure defaults or crash.
- Using
os.environ['VAR']withoutget: This raises a KeyError if the variable is missing. Usegetwith a default instead. - Hardcoding secrets: Avoid putting sensitive info directly in your code; use environment variables instead.
- Forgetting to load .env files: Flask does not load .env files automatically; use packages like
python-dotenvto load them in development.
python
import os # Wrong: raises KeyError if SECRET_KEY not set # secret_key = os.environ['SECRET_KEY'] # Right: safe access with default secret_key = os.environ.get('SECRET_KEY', 'defaultsecret')
Quick Reference
Remember these tips when using environment variables in Flask:
- Use
os.environ.get('VAR_NAME')to safely access variables. - Set environment variables outside your code (e.g., in your OS or .env files).
- Use
python-dotenvto load .env files during development. - Never commit secrets or keys to version control.
Key Takeaways
Use os.environ.get('VAR_NAME') to access environment variables safely in Flask.
Set sensitive data like secret keys outside your code to keep them secure.
Use python-dotenv to load .env files automatically during development.
Avoid KeyError by providing default values when accessing environment variables.
Never hardcode secrets or commit them to version control.