os.getenv retrieves a named environment variable from Python, helping move database credentials out of application code and into deployment configuration. section 3.7
import os … POSTGRES_USER = os.getenv("POSTGRES_USER") POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD") … DATABASE_URL = f"dbname={POSTGRES_USER} user={POSTGRES_USER} ➥ password={POSTGRES_PASSWORD} host=postgres port=5432"
The API imports os, reads PostgreSQL credentials with os.getenv, and builds a database connection string from the returned values. section 3.7
Optional fallback
os.getenv("POSTGRES_USER", "postgres") returns the configured value when present and "postgres" when the variable is absent. Omitting the fallback can expose configuration mistakes instead of allowing an accidental connection. section 3.7
A practical configuration flow:
- Define POSTGRES_USER and POSTGRES_PASSWORD in an environment file. section 3.7
- Load that file into Docker Compose services with env_file. section 3.7
- Read the variables in Python and use them in the PostgreSQL connection string. section 3.7
