How does one return a dict
like object through protoRPC
?
I tried using the FieldList
to no avail. I only see the following field definitions:
'IntegerField',
'FloatField',
'BooleanField',
'BytesField',
'StringField',
'MessageField',
'EnumField',
There are two scenarios:
1) Your dict
has a well-defined schema: This is the best use case for ProtoRPC and if possible you should try to fit it into a schema. In this case, you would use a MessageField
with some Message
class that matches the schema in your dictionary.
For example, instead of
{'amount': 31, 'type': 'fish', mine: False}
you could define
from protorpc import messages
class MyCatch(messages.Message):
amount = messages.IntegerField(1)
type = messages.StringField(2)
mine = messages.BooleanField(3)
and then use this message definition in a field via
messages.MessageField(MyCatch, index, ...)
2) Your dict
does not have a well-defined schema: In this case you can use json
to dump your dictionary to a string and request ensure_ascii=True
to make sure the return type is a bytes (str
) object. Then you can just use a BytesField
.
For example:
import json
class MyMessage(messages.Message):
some_dict = messages.BytesField(1)
my_dict = {'amount': 31, 'type': 'fish', mine: False}
message = MyMessage(some_dict=json.dumps(my_dict, ensure_ascii=True))
The use of ensure_ascii
is optional as True
is the default, but this may change depending on your environment.
Instead you could use pickle
to serialize your dictionary. The method pickle.dumps
always outputs ASCII/binary, so by swapping out json.dumps
for pickle.dumps
and dropping the ensure_ascii=True
, you'd have the same outcome.