▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Configuration and secrets
Environment variables and .env files done right.
🎬 Video version coming soon — read it now
API keys, database URLs and settings like "debug mode" change between your laptop, a test server and production. They belong in configuration, not in code.
Twelve-factor rule: config in the environment
Read settings from environment variables:
Using os.environ["X"] for required values means a missing key fails immediately at startup with a clear KeyError, not hours later in the middle of a job.
.env files for local development
Typing export every time is tedious. Keep local settings in a .env file:
Then:
- Add
.envto.gitignorebefore your first commit. - Commit a
.env.examplewith the names and dummy values, so teammates know what's needed.
Validated settings with Pydantic
For bigger projects, pydantic-settings reads the environment into a typed, validated object:
Field names map to environment variables, case-insensitively.
In production
Hosting platforms (Render, Railway, Fly.io, AWS and others) have a secrets or environment variables page. Paste values there; never into code or a committed file.
If a secret was committed
Deleting it in the next commit is not enough: it's still in git history, and bots scan GitHub constantly. Revoke the key at the provider immediately and create a new one. Then clean the history if needed.
What's not a secret
Settings like timeouts, feature flags and model names can have sensible defaults in code and be overridden by the environment. Keep defaults safe: debug off, strict limits on.
In one line
Read config from environment variables, use .env (gitignored) locally with a committed .env.example, validate settings at startup, and revoke any leaked key at once.
Share with a friend