Created
December 4, 2021 11:19
-
-
Save apibakery/205fa1ae264ba65acbd7c53dd90d8cb5 to your computer and use it in GitHub Desktop.
Environment variable parsing for Django projects using dotenv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Simple and explicit environment variable parsing for Django projects | |
# Uses the "dotenv" package to automatically load .env file | |
# See https://apibakery.com/blog/django-settings-howto/ | |
# | |
# Written by Senko Rasic <senko@apibakery.com> | |
# Released into Public Domain | |
import os | |
from dotenv import load_dotenv | |
load_dotenv() | |
__all__ = [ | |
"BASE_DIR", "ABS_PATH", | |
"ENV_BOOL", "ENV_STR", "ENV_INT", | |
"ENV_DEC", "ENV_LIST", | |
] | |
# Assume we're in a subdirectory of project root (eg. "settings/env.py") | |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
def ABS_PATH(*args): | |
"""Given a relative path within project, returns the absolute path""" | |
return os.path.join(BASE_DIR, *args) | |
def ENV_BOOL(name, default=False): | |
""" | |
Parses env variable as a boolean and returns it. | |
If not set or can't be parsed, returns the default value, | |
or False if default isn't given. | |
""" | |
if name not in os.environ: | |
return default | |
if os.environ[name].lower() in ["true", "yes", "1"]: | |
return True | |
elif os.environ[name].lower() in ["false", "no", "0"]: | |
return False | |
else: | |
return default | |
def ENV_STR(name, default=None): | |
""" | |
Returns env variable. If it's not set, returns the default. | |
""" | |
return os.environ.get(name, default) | |
def ENV_INT(name, default=None): | |
""" | |
Parses env variable as an integer and returns it. | |
If not set or can't be parsed, returns the default value, | |
or None if default isn't given. | |
""" | |
try: | |
return int(os.environ.get(name, default)) | |
except ValueError: | |
return default | |
def ENV_DEC(name, default=None): | |
""" | |
Parses env variable as a Decimal and returns it. | |
If not set or can't be parsed, returns the default value, | |
or None if default isn't given. | |
""" | |
from decimal import Decimal | |
try: | |
return Decimal(os.environ.get(name, default)) | |
except ValueError: | |
return default | |
def ENV_LIST(name, separator, default=None): | |
""" | |
Parses env variable as list of strings split by a separator. | |
Returns the parsed list, or the default if it wasn't defined. | |
""" | |
if default is None: | |
default = [] | |
if name not in os.environ: | |
return default | |
return os.environ[name].split(separator) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment