forked from twilio/twilio-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize.py
More file actions
93 lines (71 loc) · 2.26 KB
/
serialize.py
File metadata and controls
93 lines (71 loc) · 2.26 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
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
import datetime
import json
from twilio.base import values
def iso8601_date(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime):
return str(d.date())
elif isinstance(d, datetime.date):
return str(d)
elif isinstance(d, str):
return d
def iso8601_datetime(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date):
return d.strftime("%Y-%m-%dT%H:%M:%SZ")
elif isinstance(d, str):
return d
def prefixed_collapsible_map(m, prefix):
"""
Return a dict of params corresponding to those in m with the added prefix
"""
if m == values.unset:
return {}
def flatten_dict(d, result=None, prv_keys=None):
if result is None:
result = {}
if prv_keys is None:
prv_keys = []
for k, v in d.items():
if isinstance(v, dict):
flatten_dict(v, result, prv_keys + [k])
else:
result[".".join(prv_keys + [k])] = v
return result
if isinstance(m, dict):
flattened = flatten_dict(m)
return {"{}.{}".format(prefix, k): v for k, v in flattened.items()}
return {}
def boolean_to_string(bool_or_str):
if bool_or_str == values.unset:
return bool_or_str
if bool_or_str is None:
return bool_or_str
if isinstance(bool_or_str, str):
return bool_or_str.lower()
return "true" if bool_or_str else "false"
def object(obj):
"""
Return a jsonified string represenation of obj if obj is jsonifiable else
return obj untouched
"""
if isinstance(obj, dict) or isinstance(obj, list):
return json.dumps(obj)
return obj
def map(lst, serialize_func):
"""
Applies serialize_func to every element in lst
"""
if not isinstance(lst, list):
return lst
return [serialize_func(e) for e in lst]