Untitled

 avatar
unknown
python
a year ago
924 B
4
Indexable
import importlib
import os
import tempfile

def get_data(data:bytes,proto:str):
    with tempfile.NamedTemporaryFile(mode="w",delete=True) as proto_file:
        proto_file.write(proto_content1)
        proto_file.flush()

        proto_file_path = os.path.dirname(proto_file.name)
        proto_file_name = os.path.basename(proto_file.name)
        pb2_path = f"{proto_file.name}_pb2.py"

        os.system(f"protoc --proto_path={proto_file_path} --python_out={proto_file_path} {proto_file_name}")
    
    tmp_lib = importlib.util.spec_from_file_location('tmp_lib',location=pb2_path)
    module = importlib.util.module_from_spec(tmp_lib)
    tmp_lib.loader.exec_module(module)
    
    return module.Person.FromString(data)

proto_content1 = """syntax = "proto3";
message Person {
  string name = 1;
  int32 id = 2;
  string email = 3;
}"""

b = b'\n\x08zhangsan\x10\x9a\x05\x1a\r456789@qq.com'

get_data(b,proto_content1)
Editor is loading...
Leave a Comment