使用Python在Zapier中获取图像

问题描述 投票:2回答:1

我正在尝试使用Python代码步骤在Zapier中下载图像。这是一些示例代码(但它似乎不起作用):

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。)谢谢。

python zapier
1个回答
2
投票

看起来你需要一个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_serializable}不应该给出错误。

从字符串中恢复图像并保存到文件:

with open("imageToSave.png", "wb") as f: 
    f.write(base64.decodebytes(img_serializable.encode('utf-8'))) 

使用codecs也是如此,它是标准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')) 
© www.soinside.com 2019 - 2024. All rights reserved.