Reading options from Command-line, from Environment Variables or a .env File
@January 3, 2024
Happy New Year! This is a short read on simplifying configuration and launch management using python’s decouple library.
In the world of software development, managing configuration settings is a crucial aspect. Python Decouple is a lightweight library that streamlines the process of separating configuration options from your code. This handy library enables you to read startup options and configurations from environment variables, or a .env (dot-env) file with remarkable ease and integrates well with the argparse library.
Why Use Python Decouple?
The philosophy behind Python Decouple is simple: your code should be independent of its configuration. This separation not only enhances security (by keeping sensitive information out of your codebase) but also increases flexibility, making your application environment agnostic. Especially dockerized/containzerized applications benefit from reading in their launch arguments from env variables or a mounted .env file.
Key Features of Python Decouple:
- Versatility in Configuration Sources: Python Decouple can read configuration data from three primary sources - command line arguments, environment variables, and .env files. This flexibility allows developers to choose the most suitable source for their needs.
- Type Casting: It automatically converts values to Python's standard data types, simplifying the handling of numeric, boolean, and other types of settings.
- Simple Syntax: The library's straightforward syntax makes it easy to integrate into your existing Python projects.
- Fallback Values: You can define default values for your configurations, ensuring your application runs smoothly even if certain settings are missing.
How to Use Python Decouple:
- Installation: In your development environment install Python Decouple via pip or even better, add it to your
requirements.txt
orsetup.py
: - Reading from .env File:
Create a
.env
file in a folder inside your deployment and add your configurations: - Accessing Configurations in Code:
In your Python code, import
config
fromdecouple
and use it to access your settings. Here’s an example of decouple and argparse working in conjunction: - Reading from Environment Variables:
Alternatively, you can set the configurations as environment variables and access them in a similar manner.
LOG_LEVEL=INFO myapp
(wheremyapp
is the generated python project binary) - Command Line Arguments:
While Python Decouple focuses on .env files and environment variables, it integrates well with libraries like
argparse
to handle command line arguments as the example above shows.
pip install python-decouple
LOG_LEVEL=DEBUG
TELEGRAM_BOT_BOKEN=yourbottoken123
import argparse
import sys
from decouple import config
# from myapp import MyApp
# from myapp.logger import set_log_level
class AppStarter:
def __init__(self):
self.app = None
def run(self, argv):
options = argparse.ArgumentParser()
options.add_argument('-b', '--telegram-bot-token',
help="Telegram bot token. Also via env TELEGRAM_BOT_TOKEN or .env")
options.add_argument('-c', '--telegram-chat-id',
help="Telegram chat ID (negative number for channel). Also via env TELEGRAM_CHAT_ID or .env")
options.add_argument('-l', '--loglevel',
help="Log level. Also via env LOGLEVEL or .env. Valid values are DEBUG, INFO, WARN, ERROR etc.")
args = options.parse_args(argv[1:])
args.telegram_bot_token = args.telegram_bot_token or config('TELEGRAM_BOT_TOKEN')
args.telegram_chat_id = args.telegram_chat_id or config('TELEGRAM_CHAT_ID')
args.loglevel = args.loglevel or config('LOGLEVEL')
# if args.loglevel:
# set_log_level(args.loglevel)
# self.app = MyApp(args)
# ret = self.app.run()
sys.exit(ret)
def main():
app = AppStarter()
app.run(sys.argv)
Python Decouple along with argparse offers a straightforward and flexible way to handle configuration and launch settings in Python applications. By separating the configuration from the code, it promotes a cleaner, more secure, and more manageable codebase. Whether you’re working on a small script or a large-scale application, Python Decouple can be a valuable addition to your toolkit. Enjoy.