繁体   English   中英

如何使用python通过POST请求向WordPress REST API发送带有元数据(标题、描述)的媒体

[英]how to send media with meta data (caption, description) via POST request to WordPress REST API with python

我正在尝试使用 python 请求向 Wordpress REST API 发出 POST 请求。 POST 数据包含图像和元数据(如标题和描述)。 图片上传成功没有任何问题,但没有包含任何标题,描述,...数据。 我错过了什么? 这是我的代码

    header = {'Authorization': 'Basic ' + token.decode('utf-8'),
              "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
    }

    media = {
         'file': open("img.jpg","rb"),
         'title': "title",
         'caption': "caption",
         'description': "description",
         'alt_text': "alt_text"
    }

    image =  requests.post(url + '/media' , headers= header, files= media,timeout=15)

我认为您可能需要提出两个请求,第一个是上传图片,第二个是设置标题和描述。 以下代码应该对您有用(主要取自 [1]):

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

media = {'file': open('img.jpg','rb')}

# first request uploading the image
image = requests.post(url + '/media', headers=headers, files=media) 

# get post-id out of the response to the first request
postid =json.loads(image.content.decode('utf-8'))['id'] 

# set the meta data
post = {'title': 'title',
        'caption': 'caption',
        'description': 'description',
        'alt_text': 'alt_text'
       }

# second request to send the meta data
req = requests.post(url + '/media/'+str(postid), headers=headers, json=post) 

[1] https://github.com/timsamart/wp_upload_media

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM