无法对发布/订阅消息中的列表进行编码

2024-09-30 08:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图在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

Tags: projectmessagedatatopicbytesobjecttimetype
2条回答

函数b64encode()需要一个bytes-like对象并返回编码的字节

函数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,
                    }
        }

相关问题 更多 >

    热门问题