forked from ericmoritz/dict-to-protobuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict_to_protobuf.py
188 lines (139 loc) · 4.85 KB
/
dict_to_protobuf.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
from fp.monads.maybe import Maybe, Nothing
from fp.collections import lookup
from fp import p, pp, c
class MissingKeyError(Exception):
def __init__(self, key, pb):
pb_name = _pb_name(pb)
msg = "{key!r} not described in the {pb_name!r} message".format(**locals())
Exception.__init__(self, msg)
self.key = key
self.pb = pb
def dict_to_protobuf(mod, pb, data, strict=False, state=None):
"""
Converts a dict to a protobuf message
>>> import example_pb2
>>> ex = dict_to_protobuf(
... example_pb2,
... example_pb2.Example(),
... {'key': '1', 'values': ['1','2','3'], 'nested': {'value': '1'},
... 'nested_values': [{'value': '1'}, {'value': '2'}]}
... )
>>> ex.key
'1'
>>> ex.values
['1', '2', '3']
>>> ex.nested.value
'1'
>>> ex.nested_values[0].value
'1'
>>> ex.nested_values[1].value
'2'
Test the different ways that strict=True will
throw an error
At the root:
>>> ex = dict_to_protobuf(
... example_pb2,
... example_pb2.Example(),
... {'unknown-key': 1},
... strict=True)
Traceback (most recent call last):
...
MissingKeyError: 'unknown-key' not described in the 'example_pb2.Example' message
In a nested message:
>>> ex = dict_to_protobuf(
... example_pb2,
... example_pb2.Example(),
... {'nested': {'unknown-key': 1}},
... strict=True)
Traceback (most recent call last):
...
MissingKeyError: 'unknown-key' not described in the 'example_pb2.Example.Nested' message
In a repeated nested message:
>>> ex = dict_to_protobuf(
... example_pb2,
... example_pb2.Example(),
... {'nested_values': [{'unknown-key': 1}]},
... strict=True)
Traceback (most recent call last):
...
MissingKeyError: 'unknown-key' not described in the 'example_pb2.Example.Nested' message
"""
if state is None:
state={'strict': strict}
else:
strict = state.get('strict', False)
for key, value in data.iteritems():
enforce_strictness(strict, pb, key)
if field_exists(pb, key):
if is_message(pb, key, value):
update_message(mod, pb, key, value, state)
elif is_repeated(pb, key, value):
update_repeated(mod, pb, key, value, state)
elif is_value(pb, key, value):
update_value(mod, pb, key, value, state)
return pb
def enforce_strictness(strict, pb, key):
if strict and not field_exists(pb, key):
raise MissingKeyError(key, pb)
def is_message(pb, key, value):
return type(value) is dict
def is_repeated(pb, key, value):
return type(value) is list
def is_value(pb, key, value):
return not is_message(pb, key, value) and not is_repeated(pb, key, value)
def update_message(mod, pb, key, value, state):
dict_to_protobuf(mod, getattr(pb, key), value, state=state)
def update_repeated(mod, pb, key, values, state):
clsM = load_pb_class(mod, pb, key)
if clsM.is_just:
cls = clsM.from_just
for value in values:
obj = getattr(pb, key).add()
dict_to_protobuf(mod, obj, value, state=state)
else:
for value in values:
getattr(pb, key).append(value)
def update_value(mod, pb, key, value, state):
try:
setattr(pb, key, value)
except Exception, err:
raise Exception("Error setting {key!r} to {value!r}: {err}".format(
key=key,
value=value,
err=err))
def maybe_getattr(attr, obj):
return Maybe.catch(lambda: getattr(obj, attr))
def maybe_getnested_attr(obj, *attrs):
m = Maybe.ret(obj)
for attr in attrs:
m = m.bind(p(maybe_getattr, attr))
return m
def load_pb_class(mod, pb, key):
"""
Loads a class for a key
>>> import example_pb2
>>> load_pb_class(example_pb2, example_pb2.Example(), 'nested')
Just(<class 'example_pb2.Nested'>)
>>> load_pb_class(example_pb2, example_pb2.Example(), 'nested_values')
Just(<class 'example_pb2.Nested'>)
>>> load_pb_class(example_pb2, example_pb2.Example(), 'xxx')
Nothing
"""
return lookup(Maybe, _fields_by_name(pb), key).bind(
pp(maybe_getnested_attr, 'message_type', 'full_name')).bind(
lambda full_name: maybe_getnested_attr(mod, *full_name.split('.')))
def field_exists(pb, key):
return key in _fields_by_name(pb)
def _fields_by_name(pb):
return pb.DESCRIPTOR.fields_by_name
def _pb_name(pb):
"""
>>> import example_pb2
>>> _pb_name(example_pb2.Example)
'example_pb2.Example'
>>> _pb_name(example_pb2.Example.Nested)
'example_pb2.Example.Nested'
"""
mod = pb.__module__
full_name = pb.DESCRIPTOR.full_name
return '{mod}.{full_name}'.format(mod=mod, full_name=full_name)