This repository has been archived by the owner on Feb 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
env.py
53 lines (46 loc) · 1.54 KB
/
env.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Thanks to the authors of django-dotenv and django-getenv for the inspiration!
import ast
import os
import warnings
def read_dotenv(filename='.env'):
"""
Writes the values in ``.env`` in the same folder as this file into
``os.environ`` if the keys do not exist already.
Example::
DATABASE_URL=...
CACHE_URL = '...'
SECRET_KEY = "...."
"""
path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
filename)
if not os.path.isfile(path):
warnings.warn('%s not a file, not reading anything' % filename)
return
# Not sure whether we should try handling other encodings than ASCII
# at all...
with open(path) as f:
for line in f:
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = [v.strip('\'" \t') for v in line.split('=', 1)]
os.environ.setdefault(key, value)
def env(key, default=None, required=False):
"""
An easier way to read values from the environment.
The value is converted to one of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
"""
try:
value = os.environ[key]
return ast.literal_eval(value)
except (SyntaxError, ValueError):
return value
except KeyError:
if required:
raise Exception(
'Required key %s not available in environment'
% repr(key))
return default