如何使用Python字典创建Protobuf结构? [英] How do you create a Protobuf Struct from a Python Dict?

查看:79
本文介绍了如何使用Python字典创建Protobuf结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下属性错误

AttributeError:"Struct"对象没有属性"fields"

AttributeError: 'Struct' object has no attribute 'fields'

如果我想使用update 方法.py"rel =" noreferrer> google.protobuf.internal.well_known_types.Struct

if I want to use the update method of google.protobuf.internal.well_known_types.Struct

Protobuf版本是3.71.

Protobuf version is 3.71.

MWE :

from google.protobuf.internal.well_known_types import Struct

s = Struct()
s.update({"key": "value"})


此问题的更大范围是,我想使用python中的 google.protobuf.Struct 字段创建一条消息,以发送给传递给生成的RPC客户端.


The bigger context of this question is that I want to create a message with a google.protobuf.Struct field in python for sending to pass to the generated RPC client.

有人可以帮忙吗?

推荐答案

好吧,写完问题后,我立即发现了如何做到这一点.将答案留给可能最终遇到此问题的其他人.

Ok, I immediately found out how to do this after writing the question. Leaving the answer for anyone else who might end up having this problem.

我们必须从 google.protobuf.struct_pb2 导入 Struct .然后 update 可以正常工作.

We have to import Struct from google.protobuf.struct_pb2. Then update will work without a problem.

因此

from google.protobuf.struct_pb2 import Struct

s = Struct()
s.update({"key": "value"})

将返回具有表示形式的对象

will return an object with representation

fields {
  key: "key"
  value {
    string_value: "value"
  }
}

这篇关于如何使用Python字典创建Protobuf结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆