在 Zapier 中使用 Python 获取图像 [英] Use Python to get image in Zapier

查看:32
本文介绍了在 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')) 

这篇关于在 Zapier 中使用 Python 获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆