Code

Configure with Environment Variables

The same code often runs in different places: your laptop, a test server, production. Settings that change between them (ports, debug mode, API keys) belong in environment variables, not in the code.

import os

port = int(os.environ.get("LANTERN_PORT", "8000"))

os.environ works like a dict of strings. Always:

  1. Give a sensible default with .get(key, default).
  2. Convert the type yourself, because everything arrives as text.
  3. Fail with a clear message when a value is wrong.

Watch out: bool("false") is True, because any non-empty string is truthy! Compare against a set of accepted words instead.

Keep secrets (passwords, tokens) out of your code and out of git. Read them from the environment, which is exactly what this pattern does.

Taking env as a parameter (defaulting to os.environ) makes the function easy to test with a plain dict.

Assignment

Write load_config(env=None). Use os.environ when env is None. Return a dict with:

  1. "name": LANTERN_NAME, default "lantern-network"
  2. "port": LANTERN_PORT as an int, default 8000. If it isn't a number, raise ValueError with a message that mentions LANTERN_PORT.
  3. "debug": True only if LANTERN_DEBUG (any case, ignoring spaces) is one of 1, true, yes, on. Default False.