如何使用Python中的wordpress api上传图像?

2024-04-27 00:42:31 发布

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

我希望你很好

我想从我的计算机上传wordpress库中的图像。 我用Python编写了几行使用WordPressAPI的代码

当我使用“内容类型”:“应用程序/x-www-form-urlencoded” 但是,添加的内容不是图像

当我用“Content Type”:“image/jpg”更改它时,我会收到一条错误消息,上面写着: 错误403请将此错误屏幕转发给网站所有者

我应该怎么做,联系我的网络托管公司

谢谢大家的帮助

这是我的密码:

from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import base64
import json
import time
import os


user = "user"
password = "pass"

url = "https://example.com/wp-json/wp/v2"
data_string = user + ':' + password

token = base64.b64encode(data_string.encode())

# headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}
headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'application/x-www-form-urlencoded','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}



video = {
    "title": "test",
    "description": "description",
    "media-type": "image",
}

r = requests.post(url + "/media", headers=headers, json=video)
print(r.text)

Tags: test图像imageimporttokenjson内容www
1条回答
网友
1楼 · 发布于 2024-04-27 00:42:31

我用这个代码解决了这个问题

from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import base64
import json
import time
import os


user = "user"
password = "pass"

url = "https://example.com/wp-json/wp/v2"
data_string = user + ':' + password

token = base64.b64encode(data_string.encode())

headers = {'Authorization': 'Basic ' + token.decode('utf-8')}


image = {
    "file": open("toto.png", "rb"),
    "caption": "caption",
    "description": "description",
}

r = requests.post(url + "/media", headers=headers, files=image)
print(r.text)
print(r)

相关问题 更多 >