create switchable test and live modes in python in python

One way to achieve switchable test and live modes in Python is by leveraging environment variables. Here's an example code snippet:

main.py
import os

if os.environ.get('MY_APP_ENV') == 'test':
    # setup test configurations
    db_url = 'test_db_url'
    api_key = 'test_api_key'
else:
    # setup production configurations
    db_url = 'prod_db_url'
    api_key = 'prod_api_key'

# code that interacts with db_url and api_key
289 chars
13 lines

In the above code, we check the value of an environment variable named MY_APP_ENV. If it is set to test, we configure the app for the test mode, and if it is not set (or set to any other value), we configure the app for the live mode.

By setting MY_APP_ENV environment variable, we can easily switch between the two modes without having to modify the code. We can set this variable in different ways depending on our deployment environment (e.g., through shell scripts, Docker containers, cloud providers' environment variable settings, etc.).

gistlibby LogSnag