-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathenv.py
71 lines (50 loc) · 1.48 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
"""Parses env variables into a human friendly dictionary."""
from os import environ
try: # pragma: no cover
from urllib.parse import urlparse as _urlparse
except ImportError: # pragma: no cover
from urlparse import urlparse as _urlparse
def lower_dict(d):
"""Lower cases string keys in given dict."""
_d = {}
for k, v in d.items():
try:
_d[k.lower()] = v
except AttributeError:
_d[k] = v
return _d
def urlparse(d, keys=None):
"""Return a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d
def prefix(prefix):
"""
Return dictionary with all environment variables starting with prefix.
The elements of the dictionary are all lower cased and stripped of prefix.
"""
d = {}
e = lower_dict(environ.copy())
prefix = prefix.lower()
for k, v in e.items():
try:
if k.startswith(prefix):
k = k[len(prefix):]
d[k] = v
except AttributeError:
pass
return d
def map(**kwargs):
"""
Return a dictionary of the given keyword arguments mapped to os.environ.
The input keys are lower cased for both the passed in map and os.environ.
"""
d = {}
e = lower_dict(environ.copy())
for k, v in kwargs.items():
d[k] = e.get(v.lower())
return d