google.protobuf python



我正在尝试在Python中实现protobuf文件的验证。我不想使用外包装。

我试过了:

desc_set = descriptor_pb2.FileDescriptorSet()
descriptor_bytes = str.encode(descriptor)
desc_set.ParseFromString(descriptor_bytes)
pool = descriptor_pool.DescriptorPool()
desc = descriptor_pb2.FileDescriptorProto()
descriptor_bytes = str.encode(descriptor)
desc.ParseFromString(descriptor_bytes)

for fd in desc_set.file:
pool.Add(fd)
proto_msg = MessageFactory(pool).GetPrototype(pool.FindMessageTypeByName(desc_set.file[0].package))
proto_msg.FromString(bytearray(b'nx05Adnan'))

在最后一行中,我定义了原型文件:

syntax = "proto2";
package employees;
message Employees {
required string Name = 1;
required int32 age = 2;
}

我将bytearray(<msg>)发送到FromString()方法

我预计会出现解析错误,因为中缺少年龄字段,而在proto文件中,该字段是必需的。

在这种情况下,我如何获得解析错误?

您的代码是不可复制的,对我来说不起作用:

Python 3.10.6
grpcio==1.50.0
grpcio-tools==1.50.0
protobuf==4.21.9

但是:

将(!(字段重命名为name(根据样式指南(:

syntax = "proto2";
package employees;
message Employees {
required string name = 1;
required int32 age = 2;
}

和:

python3 
-m grpc_tools.protoc 
--proto_path=${PWD} 
--python_out=${PWD} 
$PWD/employees.proto
python3 
-m grpc_tools.protoc 
--include_imports 
--include_source_info 
--proto_path=${PWD} 
--descriptor_set_out=${PWD}/employees.pb 
$PWD/employees.proto

和:

import google.protobuf.descriptor_pb2 as descriptor_pb2
import google.protobuf.descriptor_pool as descriptor_pool
from google.protobuf.message_factory import MessageFactory
import employees_pb2
# Create a new Employees
e1 = employees_pb2.Employees(
name="Adnan",
age=21,
)
# Serialize
s = e1.SerializeToString()
print(s)
# Create by parsing serialized string
e2 = employees_pb2.Employees()
e2.ParseFromString(s)
print(e2)
# Create by parsing example serialized string
# No error is thrown
e3 = employees_pb2.Employees()
e3.ParseFromString(b'nx05Adnan')
print(e3)

收益率:

b'nx05Adnanx10x15'
name: "Adnan"
age: 21
name: "Adnan"

注意ParseFromString在此处(也(未抛出错误

我不熟悉使用Python来处理描述符:

with open("employees.pb", mode="rb") as file:
descriptor = file.read()
desc_set = descriptor_pb2.FileDescriptorSet()
desc_set.ParseFromString(descriptor)
pool = descriptor_pool.DescriptorPool()

for fd in desc_set.file:
pool.Add(fd)
employees = MessageFactory(pool).GetPrototype(
pool.FindMessageTypeByName("employees.Employees"))
e4 = employees()
e4.ParseFromString(b'nx05Adnan')
print(e4)

收益率:

name: "Adnan"

注意ParseFromString在此处(也(未抛出错误

似乎ParseFromString没有验证。

相关内容

  • 没有找到相关文章

最新更新