Skip to content
IT Vizag
← Production Python

▶ 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

Lesson 4 of 10 · 2 min read

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:

🔒 Code example: sign up free (above) to unlock it.

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:

🔒 Code example: sign up free (above) to unlock it.
🔒 Code example: sign up free (above) to unlock it.
🔒 Code example: sign up free (above) to unlock it.

Then:

  1. Add .env to .gitignore before your first commit.
  2. Commit a .env.example with 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:

🔒 Code example: sign up free (above) to unlock it.

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.

Tip: Install a pre-commit secret scanner such as gitleaks. It blocks commits that contain anything that looks like a key, which is a cheap insurance policy.

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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend