The Python os module retrieves operating-system environment variables so application containers can use database credentials without hardcoding them in API code. section 3.7
Use os.getenv to connect container configuration with application settings:
- Define POSTGRES_USER and POSTGRES_PASSWORD in an environment file. section 3.7
- Configure Docker services with the env_file directive. section 3.7
- Import os and retrieve each variable with os.getenv. section 3.7
- Optionally provide a default value when a variable is absent. section 3.7
Building a database connection string
Read POSTGRES_USER and POSTGRES_PASSWORD with os.getenv, then interpolate them into DATABASE_URL alongside the PostgreSQL host and port. 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"
Shows the Python configuration pattern for reading credentials and constructing DATABASE_URL. section 3.7




