将列表转换为 Google pub/sub 的字节串

use*_*877 5 python python-3.x google-cloud-platform

我在从 python 客户端向 google cloud pub/sub 服务发布消息时遇到问题。

我有基于休息的公共 API,它返回 JSON 数据。返回的数据以字典形式存储在列表中。

我已将字典中的值提取到列表中,并使用 bytes() 转换为字节字符串,但它仍然抛出下面的异常。

['EB', 'Pulaski', '2018-03-06 21:50:18.0', '0.5', '41.7930671862', '41.793140551', '-87.7136071496', 'W', 'Central Park', '-1', '1', '-87.7231602513', '55th']

response = requests.get("https://data.cityofchicago.org/resource/8v9j-bter.json")
traffic = response.json()


result_list = []
for d in traffic:
  result_list.append([v for k, v in d.items()])

for x in result_list:
  print(x)
  publisher.publish(topic_path, data = bytes(x))
Run Code Online (Sandbox Code Playgroud)

小智 3

根据此处的 Python 示例,看起来您应该使用 x.encode('utf-8') 而不是 bytes(x) 来转换为字节串: https: //cloud.google.com/pubsub/docs/publisher#publish - 发送至主题的消息