Environment Variables (.env)
Environment variables are the standard way to configure apps.
Examples:
SECRET_KEYSECRET_KEYDATABASE_URLDATABASE_URLMAIL_USERNAMEMAIL_USERNAMEMAIL_PASSWORDMAIL_PASSWORD
Why env vars?
- keeps secrets out of code
- same container/code can run in dev/staging/prod
Local .env files
In local development, you can use a .env.env file.
Common library:
python-dotenvpython-dotenv
Install:
pip install python-dotenvpip install python-dotenvThen Flask can load .env.env automatically when using flask runflask run (depending on setup), or you can load manually.
Do not commit .env
Add .env.env to .gitignore.gitignore.
Instead commit:
.env.example.env.example
So people know what variables are required.
Accessing env vars in Python
import os
secret = os.environ.get("SECRET_KEY")import os
secret = os.environ.get("SECRET_KEY")Always define safe defaults for development, but never for production secrets.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
