Python 无法对发布/订阅消息中的列表进行编码
我正试图在python3.7中发布来自云函数的发布/订阅消息。消息是一个列表对象,我正试图对其进行编码并发布到发布/订阅主题 代码如下:Python 无法对发布/订阅消息中的列表进行编码,python,google-cloud-platform,google-cloud-pubsub,google-api-python-client,Python,Google Cloud Platform,Google Cloud Pubsub,Google Api Python Client,我正试图在python3.7中发布来自云函数的发布/订阅消息。消息是一个列表对象,我正试图对其进行编码并发布到发布/订阅主题 代码如下: projects\u list=[['test-main','my project']]\n这是我要传递的列表 for projects in projects_list: topic_name = 'projects/{project_id}/topics/{topic}'.format( project_id=os.getenv('
projects\u list=[['test-main','my project']]
\n这是我要传递的列表
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'
TypeError: Object of type bytes is not JSON serializable
有人能帮忙吗?谢谢
更新:
根据下面的回答,我对代码做了以下更改:
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**: a bytes-like object is required, not 'list'
TypeError: Object of type bytes is not JSON serializable
函数
b64encode()
需要类似于对象的字节,并返回编码的字节
函数dumps()
序列化对象并返回字符串
因此,必须将dumps()
的输出转换为字节
更改此行:
"data": base64.b64encode(projectsjson)
为此:
"data": base64.b64encode(bytes(projectsjson))
以下代码更改对我有效:
message = {
"data": base64.b64encode(bytes(projectsjson,encoding="utf8")).decode(),
"attributes": {
"batch_start_time": batch_start_time,
}
}
谢谢你,我已经更新了上面关于代码的评论change@user1403505Python的哪个版本?python3.7是我使用的版本