Protocol Buffers中Date类型字段赋值报错,求正确插入方式
问题解决:Protocol Buffers中Date类型数据的正确插入方式
错误原因
在Python的Protocol Buffers实现中,嵌套消息类型的字段不允许直接赋值对象,必须通过字段的内部属性逐一设置,或使用消息对象的CopyFrom()/MergeFrom()方法完成赋值。
正确写法1:直接设置嵌套字段的子属性
直接访问birth_date的子字段并赋值:
def School() -> proto_exp_pb2.School: message = proto_exp_pb2.School() message.prof.id = 42 message.prof.name = "My name" # 逐个设置Date类型字段的属性 message.prof.birth_date.year = today.year # 注意:month需匹配你定义的MONTH枚举值,比如proto_exp_pb2.MONTH.JANUARY或对应数字 message.prof.birth_date.month = today.month message.prof.birth_date.day = today.day message.prof.phone = "+000544454544" message.prof.address = "Seventh street" message.students.add(id=43, name="My name 2", gender=1) message.students.add(id=44, name="My name 3") return message
正确写法2:先构建Date实例,再用CopyFrom赋值
先创建完整的Date消息对象,再通过CopyFrom()方法赋值:
def School() -> proto_exp_pb2.School: message = proto_exp_pb2.School() message.prof.id = 42 message.prof.name = "My name" # 构造Date类型的消息实例 date_msg = proto_exp_pb2.Date() date_msg.year = today.year date_msg.month = today.month # 确保值符合MONTH枚举定义 date_msg.day = today.day # 使用CopyFrom完成赋值 message.prof.birth_date.CopyFrom(date_msg) message.prof.phone = "+000544454544" message.prof.address = "Seventh street" message.students.add(id=43, name="My name 2", gender=1) message.students.add(id=44, name="My name 3") return message
注意事项
如果today是Python标准库的datetime.date对象,需确保:
year和day的数值类型与Protobuf定义的uint32兼容(非负整数)month字段的值严格匹配你定义的MONTH枚举(比如枚举成员对应的数字或名称)
内容的提问来源于stack exchange,提问作者MITP
相关产品推荐
相关产品推荐

