Reputation: 101
Is there any standard way for serialization and deserialization data for gRPC transfer in Python? Something like Django REST framework for gRPC?
We store data in MongoDB, and what we need is to validate inputs coming from gRPC in some efficient way. And also neatly serialize data for transfer in the opposite direction.
Upvotes: 1
Views: 736
Reputation: 185
In our project, we are using a naive approach. Just a simple data class that is serializable to a dictionary. Fields in this class are matching to names of message entity in the gRPC proto file.
import dataclasses
@dataclasses.dataclass()
class gRPC_Mapping_Entity(object):
# These fields are matching to proto file:
some_field_a: str
some_field_b: str
# To make object serializable to dictionary
def keys(self) -> list[str]:
return [_var for _var in vars(self)
if not _var.startswith("_")]
def __getitem__(self, key):
return getattr(self, key)
# Somewhere on server side:
# ...
grpc_map = gRPC_Mapping_Entity(...)
# 'project_pb2' is automatically generated by gRPC
# 'Entity' is a message in the 'project' service
project_pb2.Entity(**dict(grpc_map))
But there might be a better way how to deal with it.
Upvotes: 2