-
Notifications
You must be signed in to change notification settings - Fork 2
/
getenv.py
104 lines (86 loc) · 2.87 KB
/
getenv.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# coding: utf-8
import os
import builtins
__version__ = '0.2.0'
class Env:
"""
Usage:
>>> app_name = 'FOO'
>>>
>>> # Set the prefix for env vars
>>> Env.set_prefix(app_name)
>>>
>>> # Define your envs
>>> ENV_PROCESSES = Env('{prefix}_PROCESSES', type=int, default=1)
>>> ENV_DEBUG = Env('{prefix}_DEBUG', type=bool, default=False)
>>> ENV_OPERATOR = Env('{prefix}_OPERATOR', default=None)
>>>
>>> # Get values
>>> processes = ENV_PROCESSES.get()
>>> debug = ENV_DEBUG.get()
>>> operator = ENV_OPERATOR.get()
"""
prefix = None
_instances = {}
supported_types = (str, int, float, bool, )
bool_true_values = ['1', 'true', 'True']
bool_false_values = ['0', 'false', 'False']
def __init__(self, key,
type=str,
default=NotImplemented):
if self.prefix is None:
raise ValueError('Please set prefix before using Env class')
self.key = key.format(prefix=self.prefix)
if type not in self.supported_types:
raise TypeError('{} is not supported'.format(type))
self.type = type
type = builtins.type
self.default = default
if default is not NotImplemented and \
default is not None and \
not isinstance(default, self.type):
raise TypeError(
'default {} ({}) should be the same type of {}'.format(
default, type(default), self.type))
Env._instances[self.key] = self
def get(self):
v = os.environ.get(self.key, None)
if v is None:
if self.default is NotImplemented:
raise ValueError('value not set')
return self.default
# convert
if self.type is str:
pass
elif self.type in [int, float]:
try:
v = self.type(v)
except ValueError:
raise ValueError('Could not convert {} to type {}'.format(v, self.type))
elif self.type is bool:
if v in self.bool_true_values:
v = True
elif v in self.bool_false_values:
v = False
else:
raise ValueError(
'for bool type only these values are allowed: {}'.format(
self.bool_true_values + self.bool_false_values))
else:
raise TypeError('Unsupported type {}'.format(self.type))
return v
@classmethod
def set_prefix(cls, prefix):
cls.prefix = prefix
class SimpleEnv:
"""
Usage:
>>> SimpleEnv.prefix = 'FOO'
>>> ENV_A = SimpleEnv('{prefix}_A')
>>> a = 'true' in ENV_A.get('true')
"""
prefix = None
def __init__(self, key):
self.key = key.format(prefix=self.prefix)
def get(self, default=None):
return os.environ.get(self.key, default)