我正试图在python3.7中发布来自云函数的发布/订阅消息。消息是一个列表对象,我正试图对其进行编码并发布到发布/订阅主题
代码如下:
projects_list=[['test-main', 'my-project']]
#这是我要通过的名单
for projects in projects_list:
topic_name = 'projects/{project_id}/topics/{topic}'.format(
project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
topic='topictest'
)
projectsjson=json.dumps(projects) #I am converting the list to json object
message = {
"data": base64.b64encode(projectsjson), #this line throws type error
"attributes": {
"batch_start_time": batch_start_time,
}
}
错误:
**TypeError**: a bytes-like object is required, not 'str'
如果我直接传递列表对象
message = {
"data": base64.b64encode(projects), #this line throws type error
"attributes": {
"batch_start_time": batch_start_time,
}
}
我得到这个错误:
**TypeError**: a bytes-like object is required, not 'list'
有人能帮忙吗?谢谢
更新: 根据下面的回答,我对代码做了以下更改:
message = {
"data": base64.b64encode(bytes(projectsjson,encoding='utf8')),
"attributes": {
"batch_start_time": batch_start_time,
}
}
但是,当我调用下面的publish方法时,会进行编码:
response = service.projects().topics().publish(
topic=topic_name, body=body
).execute()
我得到这个错误:
TypeError: Object of type bytes is not JSON serializable
函数
b64encode()
需要一个bytes-like
对象并返回编码的字节函数
dumps()
序列化对象并返回字符串因此,必须将
dumps()
的输出转换为字节更改此行:
为此:
以下代码更改对我有效:
相关问题 更多 >
编程相关推荐