Skip to content

Environment Variables (.env)

Environment variables are the standard way to configure apps.

Examples:

  • SECRET_KEYSECRET_KEY
  • DATABASE_URLDATABASE_URL
  • MAIL_USERNAMEMAIL_USERNAME
  • MAIL_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-dotenv
pip install python-dotenv

Then 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 coffee

Was this page helpful?

Let us know how we did