python - 如何使用图像字节串数据上传多个答案?

标签 python google-surveys

根据消费者调查文档,questions[].images[].data 字段采用字节数据类型。

我使用 Python 3 进行实现,但 API 给出错误,例如 Invalid ByteString 或 bytes 类型 不可 JSON 序列化。

我使用以下代码:

    import base64
    import urllib
    url = 'http://example.com/image.png'
    raw_img = urllib.request.urlopen(url).read()

    # is not JSON serializable due to json serializer not being able to serialize raw bytes
    img_data = raw_img

    # next errors: Invalid ByteString, when tried with base64 encoding as followings:
    img_data = base64.b64encode(raw_img)
    # Also tried decoding it to UTF.8 `.decode('utf-8')`

img_data 是发送到 API 的 JSON 负载的一部分。

我错过了什么吗?处理问题的图像数据上传的正确方法是什么?我查看了 https://github.com/google/consumer-surveys/tree/master/python/src 但没有这部分的示例。

谢谢

最佳答案

您需要使用网络安全/URL 安全编码。以下是有关在 Python 中执行此操作的一些文档:https://pymotw.com/2/base64/#url-safe-variations

在你的情况下,这看起来像

img_data = base64.urlsafe_b64encode(raw_img)

预计到达时间:在 Python 3 中,API 期望图像数据为 str 类型,以便可以进行 JSON 序列化,但 base64.urlsafe_b64encode 方法以 UTF-8 字节 形式返回数据。您可以通过将字节转换为 Unicode 来解决此问题:

img_data = base64.urlsafe_b64encode(raw_img)
img_data = img_data.decode('utf-8')

关于python - 如何使用图像字节串数据上传多个答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38979810/

相关文章:

javascript - 拒绝在框架中显示 'url',因为它将 'X-Frame-Options' 设置为 'SAMEORIGIN'

javascript - 如何自动随机化 46 个名称以在 Google 表格中创建 46 x 6 唯一行和列?

python - 连接两个数据框

python - 在 python 中创建命令行开关

python - 如何使用Python区分信号的下降沿?

python - Docker 身份验证中的 Flask + Bokeh

python - 使用PIL python来计算灰度等级的errorType

javascript - Google Survey Opt-in 在 DevTools 控制台选项卡中给出 404 错误