无法对 pub/sub 消息中的列表进行编码

Unable to encode list in pub/sub message

我正在尝试从 python3.7 中的云功能发布 pub/sub 消息。该消息是一个列表对象,我正在尝试对其进行编码并发布到 pub/sub 主题

代码如下: 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'

有人可以帮忙吗?谢谢

更新: 根据下面的 answer,我对代码进行了以下更改:

 message = {
        "data": base64.b64encode(bytes(projectsjson,encoding='utf8')),
        "attributes": {
        "batch_start_time": batch_start_time,
                    }
        }

编码发生,但是当我调用下面的发布方法时:

response = service.projects().topics().publish(
            topic=topic_name, body=body
        ).execute()

我收到这个错误:

TypeError: Object of type bytes is not JSON serializable

函数 b64encode() 需要 bytes-like 对象和 returns 编码字节。

函数 dumps() 序列化对象和 returns 字符串。

因此,您必须将 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,
                    }
        }