Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.3 — Configuration, Environment Variables and Secrets
Python · Example 1 of 2

os.environ: required, optional and masked

The key is fake. The mask function is what you would use before putting a key into a log line.

Settings that change between your laptop, a test server and production (and secrets such as API keys) should live outside the code, in environment variables, and be read once into a typed settings object. A secret that is committed to Git must be treated as stolen.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write get_bool(name, default=False) that reads an environment variable and returns True for 1, true or yes in any capitals, False for anything else, and default when unset.

02

Write require(*names) that returns a dictionary of the named environment variables, and raises a RuntimeError naming every missing one.

03

Write mask(secret) that keeps the first 3 and last 2 characters of a key longer than 8 characters, and returns *** for shorter ones.

Explain it without notes

01

Why should configuration and secrets live outside the source code?

02

How do you read a required and an optional environment variable in Python, and what type do you get?

03

What should you do if an API key is accidentally committed to Git?

04

What is a .env file, and how do you keep it safe?

os.environ: required, optional and masked
Sign in to run this example in your browser.

Expected output

APP_ENV: dev
DEBUG with default: 0
DEBUG is None? True
KeyError for missing variable: 'DATABASE_URL'
key in a log line: fake...56