Skip to content

Instantly share code, notes, and snippets.

@cypreess
Last active July 6, 2018 11:06
Show Gist options
  • Save cypreess/3ab7cd4f4a5ec3ad6660ed4d35ab223e to your computer and use it in GitHub Desktop.
Save cypreess/3ab7cd4f4a5ec3ad6660ed4d35ab223e to your computer and use it in GitHub Desktop.
Lightweight helpers to read settings from environement variables
import os
import re
import sys
from functools import wraps
import logging
logger = logging.getLogger(__name__)
WARN_ON_MISSING = True
NO_ARGUMENT = object()
TRUE_CHOICES = {'on', 'enabled', 'yes', 'true', '1'}
class MissingValueError(ValueError):
pass
def handle_errors(f):
@wraps(f)
def _wrapper(name, *args, **kwargs):
try:
return f(name, *args, **kwargs)
except MissingValueError as e:
if WARN_ON_MISSING:
logger.warning("Variable {key} was expected and is missing".format(key=name))
return None
else:
logger.error("Variable {key} is missing".format(key=name))
sys.exit(1)
except ValueError as e:
logger.error("Configuration error for key {key}: {message}".format(key=name, message=str(e)))
sys.exit(1)
return _wrapper
@handle_errors
def read(name, default=NO_ARGUMENT):
if name not in os.environ:
if default is NO_ARGUMENT:
raise MissingValueError
else:
return default
return os.environ[name]
@handle_errors
def read_boolean(name, default=NO_ARGUMENT):
if name not in os.environ:
if default is NO_ARGUMENT:
raise MissingValueError
else:
return default
return os.environ[name].strip().lower() in TRUE_CHOICES
@handle_errors
def read_int(name, default=NO_ARGUMENT):
value = os.environ.get(name)
if value is None:
if default is NO_ARGUMENT:
raise MissingValueError
else:
return default
else:
if not re.match('^\d+$', value):
raise ValueError('Only digits are allowed for this value'.format(name=name))
return int(value)
@handle_errors
def read_list(name, default=NO_ARGUMENT, separator=','):
"""Anythhing like VAR=1, 2, 3 will be converted to ['1', '2', '3']"""
value = os.environ.get(name)
if value is None:
if default is NO_ARGUMENT:
return []
else:
return default
return [v.strip() for v in value.split(separator) if v.strip()]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment