使用Wordpress API将数据作为图像上传到Wordpress

时间:2019-06-10 12:26:21

标签: python wordpress google-cloud-functions wordpress-rest-api

我正在尝试获取图像的URL,下载它,然后使用Wordpress API将其上传到wordpress。这是我的代码:

def upload_media(self, media_url):
    # Get the last path component
    filename = media_url.split('/')[-1]
    response = requests.get(media_url)
    if response.status_code == 200:
        image = Image.open(BytesIO(response.content))
        upload_url = self.__upload_media_url()
        headers = { "Content-Disposition": f'attachment; filename={filename}'}
        files = { 'file': image.tobytes() }
        request = requests.post(upload_url, auth=(self.username, self.password), files=files, headers=headers)
        return request

每次失败都会出现以下错误:

{'code': 'rest_upload_unknown_error', 'message': 'Sorry, this file type is not permitted for security reasons.', 'data': {'status': 500}}

最初,我有以下代码在我的本地计算机上运行。但是,因为我想在Google Cloud Functions上运行它,所以我无权访问文件系统。因此打开/关闭过程将无法进行。

def upload_media(self, media_url):
    # Get the last path component
    filename = media_url.split('/')[-1]
    response = requests.get(media_url)
    if response.status_code == 200:
        with open(filename, 'wb') as file:
            file.write(response.content)
        upload_url = self.__upload_media_url()
        headers = { "Content-Disposition": f'attachment; filename={filename}'}
        files = { 'file': open(filename, 'rb')}
        request = requests.post(upload_url, auth=(self.username, self.password), files=files, headers=headers)
        os.remove(filename)
        return request

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

根据https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.tobytes image.tobytes()产生RAW图像数据,而不是PNG或JPG压缩数据-因此,您要上传的内容是允许的类型之一。

只需删除此行:

image = Image.open(BytesIO(response.content))

然后使用:

files = { 'file':  BytesIO(response.content) }

我相信这应该可以解决您的问题。

答案 1 :(得分:0)

最终我必须对我的原始功能进行2次更改。

  1. 添加一个Content-type: image/jpeg

  2. 使用data=代替file=

这是工作功能,不需要打开/关闭任何文件:

def upload_media(self, media_url):
    # Get the last path component
    filename = media_url.split('/')[-1]
    response = requests.get(media_url)
    if response.status_code == 200:
        upload_url = self.__upload_media_url()
        headers = { "Content-Disposition": f"attachment; filename={filename}" , "Content-Type": "image/jpeg" } 
        return requests.post(upload_url, auth=(self.username, self.password), headers=headers, data=response.content)