且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

代码示例中的Gmail API错误-需要一个类似字节的对象,而不是'str'

更新时间:2021-10-06 00:36:23

找到了解决方案,替换此行:

Found a solution, replace this line:

return {'raw': base64.urlsafe_b64encode(message.as_string())}

具有:

return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

通知已添加 .encode() .decode()方法调用.

Notice added .encode() and .decode() method calls.

首先, str 对象被编码为 bytes 对象- base64.urlsafe_b64encode 在Python 3中需要它(与 str Python 2中的对象).

First, str object is encoded to bytes object - base64.urlsafe_b64encode requires it in Python 3 (compared to str object in Python 2).

然后,必须将base64编码的 bytes 对象解码回 str .这是必需的,因为 googleapiclient 库将稍后在代码中尝试对其进行 json序列化,而对于 bytes 对象是不可能的.

Then, the base64 encoded bytes object must be decoded back to str. This is needed as googleapiclient library will attempt to json serialize it later in code and that is not possible for bytes objects.