我正在尝试使用 Python 代码步骤在 Zapier 中下载图像。这是一些示例代码(但它似乎不起作用):
r = requests.get('https://dummyimage.com/600x400/000/fff')
img = r.raw.read()
return {'image_data': img}
我得到的错误是
Runtime.MarshalError:无法编码(marshal)响应:b'' 不可 JSON 序列化
有谁知道如何在 Zapier 中的 Python 代码步骤中使用请求来获取图像? (我正在尝试获取图像并将其保存到 Dropbox。) 谢谢。
最佳答案
看起来您需要一个 json 可序列化对象而不是二进制对象。
将图像转换为字符串的一种方法是使用 base64
然后对其进行编码:
使图像可序列化:
r = requests.get('https://dummyimage.com/600x400/000/fff')
img_serializable = base64.b64encode(r.content).decode('utf-8')
# check with json.dumps(img_serializable)
现在 return {'image_data': img_serialized}
不应出现错误。
从字符串中恢复图像并保存到文件:
with open("imageToSave.png", "wb") as f:
f.write(base64.decodebytes(img_serializable.encode('utf-8')))
同样使用编解码器
,它是标准Python库的一部分:
r = requests.get('https://dummyimage.com/600x400/000/fff')
content = codecs.encode(r.content, encoding='base64')
img_serializable = codecs.decode(content,encoding='utf-8')
type(img_serializable)
# Out:
# str
with open("imageToSave3.png", "wb") as f:
f.write(codecs.decode(codecs.encode(img_serializable, encoding='utf-8'), \
encoding='base64'))
关于python - 使用Python在Zapier中获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55088069/