Introduction π
Environment Variables are secure values stored outside your code β such as API keys, database URLs, secrets, or configuration settings. Using a .env file helps you keep sensitive data out of your codebase.
Note
π‘ Use .env for development, environment variables for production
π‘ Essential for APIs, automation, backend, cloud deployment
1. What Is a .env File? π€
A .env file contains key-value pairs like:
.env
API_KEY="abcdef12345"
DB_URL="postgresql://user:pass@localhost:5432/mydb"
DEBUG=Trueβ Do NOT commit this file to Git
2. Install python-dotenv π¦
install.sh
pip install python-dotenv3. How to Load .env in Python π§
load_env.py
from dotenv import load_dotenv
import os
load_dotenv() # reads .env file
print(os.getenv("API_KEY"))
print(os.getenv("DB_URL"))β os.getenv() safely retrieves environment variables
4. Using dotenv in a Project Structure π
structure.txt
project/
βββ app/
β βββ main.py
βββ .env
βββ requirements.txt5. Setting Defaults if Value Missing π―
default.py
api_key = os.getenv("API_KEY", "default-key")β Avoids crashes if variable missing
6. Environment Variables Without .env (Direct Shell) π§
Linux / macOS
bash_export.sh
export SECRET=12345
python main.pyWindows PowerShell
powershell_env.ps1
setx SECRET 123457. Protecting the .env File π
.gitignore
# Ignore sensitive files
.envβ Prevents secrets from being pushed to GitHub
8. Type Conversion for Environment Variables π
type_casting.py
DEBUG = os.getenv("DEBUG", "False").lower() == "true"
TIMEOUT = int(os.getenv("TIMEOUT", "30"))9. Using Environment Variables in Config Modules βοΈ
config.py
from dotenv import load_dotenv
import os
load_dotenv()
class Config:
API_KEY = os.getenv("API_KEY")
DEBUG = os.getenv("DEBUG") == "True"
DATABASE_URL = os.getenv("DB_URL")β Centralizes configuration
10. Using Environment Variables in FastAPI / Flask π
fastapi_example.py
from fastapi import FastAPI
import os
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
@app.get("/config")
def config():
return {"debug": os.getenv("DEBUG")}11. Nested or Multiple .env Files π
Useful for development vs production.
dotenv_multiple.py
load_dotenv(".env.development")
load_dotenv(".env.production") # overrides12. Accessing .env Inside Docker π³
docker_run.sh
docker run --env-file .env my_imageβ Docker injects variables into container
13. Testing with Environment Variables π§ͺ
test_env.py
import os
import pytest
def test_env(monkeypatch):
monkeypatch.setenv("MODE", "TEST")
assert os.getenv("MODE") == "TEST"14. Example: Secure Database Connection π
db_connection.py
import os
from dotenv import load_dotenv
import psycopg2
load_dotenv()
conn = psycopg2.connect(os.getenv("DB_URL"))
print("Connected!")15. Final Recommended .env Structure π
.env
# Application
DEBUG=True
SECRET_KEY="super-secret-key"
# Database
DB_HOST=localhost
DB_USER=user
DB_PASS=password
DB_NAME=app_db
# API keys
API_KEY_SERVICE1="key123"
API_KEY_SERVICE2="key456"Best Practices π‘
- β Never commit .env to Git
- β Use `.env.example` without secrets for sharing
- β Override with real env vars in production (not .env)
- β Use tools like dotenv, pydantic for secure configs
- β Rotate sensitive keys regularly
Conclusion π
You now understand Environment Variables (.env) in Python! Want the next topic? Try Secrets Management, Deployment Strategies, Docker Compose Env, or Pydantic Settings. Just tell me! π