Created
January 3, 2020 12:22
-
-
Save AndBondStyle/3c6cb479259d5027ba9d9c7ae65c24f4 to your computer and use it in GitHub Desktop.
[Python] Read environment variables from .env file
This file contains hidden or 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
import urllib.parse as urlparse | |
from envparse import Env | |
import json as pyjson | |
import warnings | |
import os | |
def shortcut(cast): | |
# Fix: `default` kwarg is always second argument | |
# So you can do `env.whatever('KEY', 'DEFAULT')` | |
def method(self, var, default=None, **kwargs): | |
return self.__call__(var, cast=cast, default=default, **kwargs) | |
return method | |
class Environ(Env): | |
""" | |
Thin envparse wrapper | |
""" | |
# Improved shortcuts | |
bool = shortcut(bool) | |
dict = shortcut(dict) | |
float = shortcut(float) | |
int = shortcut(int) | |
list = shortcut(list) | |
str = shortcut(str) | |
json = shortcut(pyjson.loads) | |
url = shortcut(urlparse.urlparse) | |
def read_envfile(self, path=None, **overrides): | |
# Temporarily proxy `setdefault` to `setitem` | |
# So that .env file priority is higher | |
setdefault = os.environ.setdefault | |
os.environ.setdefault = os.environ.__setitem__ | |
with warnings.catch_warnings(): | |
# Get rid of annoying warning | |
warnings.simplefilter('ignore') | |
super().read_envfile(path=path, **overrides) | |
os.environ.setdefault = setdefault | |
# Convenient global var | |
env = Environ() | |
env.read_envfile() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requirements:
envparse
(https://github.com/rconradharris/envparse).env
file should be placed in project root folderSyntax example:
Usage: