Panamap-proto adds protobuf support to panamap object mapper.
Use the package manager pip to install panamap-proto.
pip install panamap
To enabe protobuf support you must pass ProtoMappingDescriptor
in list to custom_descriptors
parameter to Mapper
constructor:
from panamap import Mapper
from panamap_proto import ProtoMappingDescriptor
mapper = Mapper(custom_descriptors=[ProtoMappingDescriptor])
After that you can set up mapping for protobuf generated classes.
To map message Simple
:
// messages.proto
syntax = "proto3";
message Simple {
string value = 1;
}
You should use folowing configuration:
from panamap import Mapper
from panamap_proto import ProtoMappingDescriptor
from messages_pb2 import Simple
mapper = Mapper(custom_descriptors=[ProtoMappingDescriptor])
mapper.mapping(Simple, SimpleData).map_matching().register()
s = mapper.map(SimpleData("abc"), Simple)
print(s.value)
# 'abc'
There is many ways to map python enums to protobuf generated enums, but the easiest way is to use values_map
utility method:
// messages.proto
enum Lang {
PYTHON = 0;
CPP = 1;
JAVA = 2;
}
from enum import Enum
from panamap import Mapper, values_map
from panamap_proto import ProtoMappingDescriptor
from messages_pb2 import Lang
class PyLang(Enum):
PYTHON = 1
CPP = 2
JAVA = 3
mapper = Mapper(custom_descriptors=[ProtoMappingDescriptor])
pairs = [
(PyLang.PYTHON, Lang.Value("PYTHON")),
(PyLang.JAVA, Lang.Value("JAVA")),
(PyLang.CPP, Lang.Value("CPP")),
]
mapper.mapping(PyLang, Lang) \
.l_to_r_converter(values_map({py: proto for py, proto in pairs})) \
.r_to_l_converter(values_map({proto: py for py, proto in pairs})) \
.register()
Contributing described in separate document.