Start learning free

LESSON 148 OF 188 · BACKEND: SHIPPING IT

Settings from the Environment in Python

Practice

The shop's code is the same on your computer and on the server, but a few settings differ: the port it listens on, and where the database file is. Don't write them into the code. The server hands them to the program as environment variables: named text values that every program it starts can read.

In Python they are in the dictionary os.environ. os.environ.get(name, default) gives you a variable's text, or the default when it isn't set. The values are always text, so a number needs int(). For example, a script that reads how many times to retry and how to greet:

import os

retries = int(os.environ.get("RETRIES", "3"))
greeting = os.environ.get("GREETING", "Hello")

Your file prints the settings the server would use. Then the check calls your load_settings() three times, with different variables set, and prints what it returns:

Port: 8000
Database: shop.db
Nothing set (your computer):
{'port': 8000, 'database_path': 'shop.db'}
PORT=5000 and DATABASE_PATH=/data/shop.db (the server):
{'port': 5000, 'database_path': '/data/shop.db'}
Only PORT=10000:
{'port': 10000, 'database_path': 'shop.db'}

Your task: write load_settings(). It reads PORT as a number, with the default "8000", and DATABASE_PATH, with the default "shop.db", and returns them in a dictionary with the keys "port" and "database_path". Below it, call it once and print the two settings after Port: and Database:.


Assignment
Follow the Coding Tutorial to read PORT and DATABASE_PATH from the environment with defaults, return them in a dictionary, and print the settings the server would use.


Hint
os.environ.get works like a dictionary's get. Put the port inside int( ), but not the path: a path is text. Without a return, the check prints None.


STEP 1 OF 7
    Ctrl + Enter to check

    Ship Env Settings in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free