尝试在wordpress api中发送图像时出错

2024-10-04 05:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用WordPressAPI向wordpress发送一个图像(我的目标是在一篇文章中使用它,也是用API创建的)。这是我的代码:

data = open(os.path.join(settings.STATIC_ROOT, "test.png"), "rb").read()
    filename="test"
    extension = "png"
    headers = {
        'authorization': 'Basic ' + token.decode('utf-8'),
        'cache-control': 'no-cache',
        'content-disposition': 'attachment; filename=%s' % filename,
        'content-type': 'image/%s' % extension
    }
    r = requests.post(url + '/media', headers=headers, data=data)

我得到以下错误的响应:

{"code":"rest_upload_sideload_error","message":"D\u00e9sol\u00e9, ce type de fichier n\u2019est pas autoris\u00e9 pour des raisons de s\u00e9curit\u00e9.","data":{"status":500}}

对于那些根本不懂法语的人,它说出于安全原因,这种类型的文件是不允许的。我不明白为什么,png不是一种非常特殊的格式,我的图像是在互联网上随机拍摄的简单图像,用于我的测试。我还尝试了一个ico文件,同样的结果。 我知道凭证部分正在工作,因为我使用它来测试用于发布帖子的API,这是有效的

谢谢你的帮助


Tags: 文件test图像apicachedatapngtype
1条回答
网友
1楼 · 发布于 2024-10-04 05:24:13

我刚想出来

我在上面发布的初始代码中有两件事需要更改。 首先,正如S.D建议的那样,我必须在我的filenam中包含扩展名,其次,将文件发送到数据中,而不是文件中。 更正的工作代码:

token = base64.b64encode(creds.encode())
    headers = {
        'Authorization': 'Basic ' + token.decode('utf-8'),
        'Content-disposition': 'attachment; filename=test.png',
        'Content-type': 'image/png'
    }
    data = open(os.path.join(settings.STATIC_ROOT, "test.png"), "rb").read();
    r = requests.post(url + '/media', headers=headers, data=data)

希望这可以帮助其他人,我真的很难找到问题的最后一部分

相关问题 更多 >