尝试使用python将google视觉响应转换为字典时出现属性错误DESCRIPTOR

Mar*_*n J 6 python google-api google-vision

我在 Windows 上,使用Python 3.8.6rc1,protobuf version 3.13.0google-cloud-vision version 2.0.0.

我的代码是:

from google.protobuf.json_format import MessageToDict
from google.cloud import vision
    
client = vision.ImageAnnotatorClient()
response = client.annotate_image({
            'image': {'source': {'image_uri': 'https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'}},
        })
MessageToDict(response)
Run Code Online (Sandbox Code Playgroud)

它失败了MessageToDict(response),我有一个attribute error: "DESCRIPTOR". 似乎response不是有效的 protobuf 对象。有人能帮我吗?谢谢

Mar*_*n J 16

这并不能真正回答我的问题,但我发现解决它并访问 protobuf 对象的一种方法是使用,response._pb因此代码变为:

response = client.annotate_image({
            'image': {'source': {'image_uri': 'https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'}},
        })
MessageToDict(response._pb)
Run Code Online (Sandbox Code Playgroud)


Roh*_*had 7

看步骤3,

第 1 步:导入该库

from google.protobuf.json_format import MessageToDict
Run Code Online (Sandbox Code Playgroud)

第 2 步:发送请求

keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
    request=request
)
Run Code Online (Sandbox Code Playgroud)

步骤 3:将响应转换为 json [看这里,添加“.pd”]

keyword_ideas_json = MessageToDict(keyword_ideas._pb) // add ._pb at the end of object
Run Code Online (Sandbox Code Playgroud)

第四步:用它做任何你想做的事json

print(keyword_ideas_json)
Run Code Online (Sandbox Code Playgroud)

同一问题的 Github:这里


Ulr*_*nus 5

也许看看这篇文章

json_string = type(response).to_json(response)
# Alternatively
import proto
json_string = proto.Message.to_json(response)
Run Code Online (Sandbox Code Playgroud)