Environment based configuration in python

Viewed 54

Folks, I am new to python. Need help ! I have four environments for my application DEV, QA, STG, PROD. I want to have four different environment files and wish to read values depending upon the environment where application is running. Also wish to pass the name of the environment from the external source and accordingly set the config file for the environment.

Please guide !!

1 Answers

To load and manage environment variables easier, take a look at python-dotenv, documentation here.

To pass command line arguments and parse them, use argparse, documentation here.

Here is a working example as I'd imagine your case:

from dotenv import load_dotenv
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument(
    'env',
    type=str,
    help='Environment to run the server in',
    choices=['DEV', 'QA', 'STG', 'PROD'],
)

args = parser.parse_args()

if args.env == 'DEV':
    load_dotenv('.env.dev')
elif args.env == 'QA':
    load_dotenv('.env.qa')
elif args.env == 'STG':
    load_dotenv('.env.stg')
elif args.env == 'PROD':
    load_dotenv('.env.prod')
Related