根据消费者调查文档,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/