Settings from the environment
Passwords, API keys and server addresses do not belong in code. Programs read them from environment variables, which a shell, a container or a hosting service sets. During development a .env file holds the same names, and it is kept out of version control.
import os
os.environ["APP_PORT"] = "8080"
port = int(os.environ.get(
"APP_PORT", "8000"))
debug = os.environ.get("APP_DEBUG") == "1"
print(port, debug)os.environbehaves like a dict of strings. Convert numbers and flags yourself..get(name, default)suits optional settings. For a required one, index with[name], so a missing value fails at startup.- A real variable overrides the
.envfile, so a server can change one value without anyone editing files.
The .env format
One NAME=value per line, with # comments, optional quotes and sometimes an export prefix:
env = '''# local settings
export APP_NAME="Shop"
APP_PORT=8000
'''
for line in env.splitlines():
print(line.partition("="))Your task
Write load_settings(text, environ) that parses .env text into a dict: skip blank lines and # comments, drop an export prefix, split at the first =, strip spaces, and remove one pair of matching quotes around the value. A key that also appears in environ (a mapping such as os.environ) takes the value from there.
The explanation opens here once every check passes.