my *_*ode 3 python rest wordpress python-requests wp-api
我认为我已经完成了90%的工作,但是最终“上传”了空白的透明图像。上传后,我收到201回应。我认为这可能是WP发现丢失图像的代理。我不确定是否传递了错误的图像(即它没有离开我的计算机),或者我是否没有根据WP的喜好正确标记图像。
from base64 import b64encode
import json
import requests
def imgUploadREST(imgPath):
url = 'https://www.XXXXXXXXXX.com/wp-json/wp/v2/media'
auth = b64encode('{}:{}'.format('USERNAME','PASS'))
payload = {
'type': 'image/jpeg', # mimetype
'title': 'title',
"Content":"content",
"excerpt":"Excerpt",
}
headers = {
'post_content':'post_content',
'Content':'content',
'Content-Disposition' : 'attachment; filename=image_20170510.jpg',
'Authorization': 'Basic {}'.format(auth),
}
with open(imgPath, "rb") as image_file:
files = {'field_name': image_file}
r = requests.post(url, files=files, headers=headers, data=payload)
print r
response = json.loads(r.content)
print response
return response
Run Code Online (Sandbox Code Playgroud)
我已经在php或node.js中看到了很多答案,但是我在理解python的语法时遇到了麻烦。感谢您的任何帮助!
我知道了!
使用此功能,我可以通过WP REST api将图像上传到我的网站(Photo Gear Hunter。),该函数返回图像的ID。然后,您可以将该ID传递到新的帖子通话中,并使其成为特色图片,或者使用它进行任何操作。
def restImgUL(imgPath):
url='http://xxxxxxxxxxxx.com/wp-json/wp/v2/media'
data = open(imgPath, 'rb').read()
fileName = os.path.basename(imgPath)
res = requests.post(url='http://xxxxxxxxxxxxx.com/wp-json/wp/v2/media',
data=data,
headers={ 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fileName},
auth=('authname', 'authpass'))
# pp = pprint.PrettyPrinter(indent=4) ## print it pretty.
# pp.pprint(res.json()) #this is nice when you need it
newDict=res.json()
newID= newDict.get('id')
link = newDict.get('guid').get("rendered")
print newID, link
return (newID, link)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3242 次 |
最近记录: |