-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathutil.py
More file actions
46 lines (38 loc) · 1.33 KB
/
util.py
File metadata and controls
46 lines (38 loc) · 1.33 KB
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
import calendar
from datetime import datetime
from chargebee import compat
def serialize(value, prefix=None, idx=None):
serialized = {}
if isinstance(value, dict):
for k, v in list(value.items()):
if isinstance(v, (dict, list, tuple)):
serialized.update(serialize(v, k))
else:
key = ''.join([
prefix or '',
'[%s]' % k if prefix is not None else k,
'[%s]' % idx if idx is not None else '',
])
serialized.update({key: get_val(v)})
elif isinstance(value, (list, tuple)):
for i, v in enumerate(value):
serialized.update(serialize(v, prefix, i))
else:
if prefix is not None and idx is not None:
key = prefix + '[' + str(idx) +']'
serialized.update({key: get_val(value)})
else:
raise TypeError("only hash or arrays are allowed as value")
return serialized
def get_val(val):
if val is None:
return ''
elif isinstance(val, bool):
return str(val).lower()
elif isinstance(val, datetime):
return calendar.timegm(val.utctimetuple())
else:
if compat.py_major_v < 3 and isinstance(val, unicode):
return val.encode("utf-8")
else:
return val;