πŸ” Python Tutorial β€” Environment Variables (.env)

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

πŸ’‘ Never hard-code secrets in Python files

πŸ’‘ 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-dotenv

3. 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.txt

5. 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.py

Windows PowerShell

powershell_env.ps1

setx SECRET 12345

7. 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")  # overrides

12. 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 πŸŽ‰

>>β€œEnvironment Variables keep your secrets safe and your apps flexible β€” master them, and your applications become truly production-ready.” ✨

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! 😊