【问题标题】:How to upload an image with the wordpress api in Python?如何在 Python 中使用 wordpress api 上传图片?
【发布时间】:2021-10-03 12:24:19
【问题描述】:

希望你没事。

我想从我的电脑上传一张图片到我的 wordpress 库中。 我在 Python 中编写了几行使用 Wordpress API 的代码。

当我使用'Content-Type'时它正在工作:'application/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)

【问题讨论】:

    标签: python wordpress api wordpress-rest-api


    【解决方案1】:

    我用这段代码解决了问题

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-23
      • 2016-08-11
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 2011-06-05
      • 2021-07-02
      • 2022-01-08
      相关资源
      最近更新 更多