在 Zapier 中使用 Python 获取图像
我正在尝试使用 Python 代码步骤在 Zapier 中下载图像.这是一些示例代码(但似乎不起作用):
I am trying to use a Python code step to download an image in Zapier. Here is some sample code (but it doesn't seem to work):
r = requests.get('https://dummyimage.com/600x400/000/fff')
img = r.raw.read()
return {'image_data': img}
我得到的错误是Runtime.MarshalError: Unable to marshal response: b'' is not JSON serializable
有谁知道我如何在 Zapier 的 Python 代码步骤中使用请求来获取图像?(我正在尝试获取图像并将其保存到 Dropbox.)谢谢.
Does anyone know how I can use requests in a Python code step in Zapier to get an image? (I am trying to get the image and save it to Dropbox.) THANKS.
看起来您需要一个 json 可序列化对象而不是二进制对象.将图像转换为字符串的一种方法是使用 base64
然后对其进行编码:
It looks like you need a json serializable object and not a binary object.
One way to convert your image to a string is to use base64
and then encode it:
使图像可序列化:
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_serializable}
应该不会报错了.
Now return {'image_data': img_serializable}
should not give errors.
从字符串中恢复图像并保存到文件:
Recover image from string and save to file:
with open("imageToSave.png", "wb") as f:
f.write(base64.decodebytes(img_serializable.encode('utf-8')))
同样使用 codecs
,这是标准 Python 库的一部分:
The same using codecs
, that is part of the standard Python library:
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'))