python에서 wordpress REST 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
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)
파일명으로 ASCII가 아닌 것을 처리하도록 개량된 버전(예: 그리스어 문자).ASC 이외의 모든 것을 변환합니다.UTF-8 이스케이프 시퀀스의 II 문자(@my Year Of Code의 원래 코드)
def uploadImage(filePath):
data = open(filePath, 'rb').read()
fileName = os.path.basename(filePath)
espSequence = bytes(fileName, "utf-8").decode("unicode_escape")
# Convert all non ASCII characters to UTF-8 escape sequence
res = requests.post(url='http://xxxxxxxxxxxxx.com/wp-json/wp/v2/media',
data=data,
headers={'Content-Type': 'image/jpeg',
'Content-Disposition': 'attachment; filename=%s' % espSequence,
},
auth=('authname', 'authpass'))
newDict=res.json()
newID= newDict.get('id')
link = newDict.get('guid').get("rendered")
print newID, link
return (newID, link)
POST HEADER는 ASCII 문자만 포함할 수 있습니다.
alt text 등 API에서 지원되는 추가 필드를 지정하려면 description etc:
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import os
fileName = os.path.basename(imgPath)
multipart_data = MultipartEncoder(
fields={
# a file upload field
'file': (fileName, open(imgPath, 'rb'), 'image/jpg'),
# plain text fields
'alt_text': 'alt test',
'caption': 'caption test',
'description': 'description test'
}
)
response = requests.post('http://example/wp-json/wp/v2/media', data=multipart_data,
headers={'Content-Type': multipart_data.content_type},
auth=('user', 'pass'))
덕분에.@my Year Of Code
.
최종 작업 코드:
import
HOST = "https://www.crifan.com"
API_MEDIA = HOST + "/wp-json/wp/v2/media"
JWT_TOKEN = "eyJxxxxxxxxjLYB4"
imgMime = gImageSuffixToMime[imgSuffix] # 'image/png'
imgeFilename = "%s.%s" % (processedGuid, imgSuffix) # 'f6956c30ef0b475fa2b99c2f49622e35.png'
authValue = "Bearer %s" % JWT_TOKEN
curHeaders = {
"Authorization": authValue,
"Content-Type": imgMime,
'Content-Disposition': 'attachment; filename=%s' % imgeFilename,
}
# curHeaders={'Authorization': 'Bearer eyJ0xxxyyy.zzzB4', 'Content-Type': 'image/png', 'Content-Disposition': 'attachment; filename=f6956c30ef0b475fa2b99c2f49622e35.png'}
uploadImgUrl = API_MEDIA
resp = requests.post(
uploadImgUrl,
# proxies=cfgProxies,
headers=curHeaders,
data=imgBytes,
)
돌아가다201
수단Created OK
response json은 다음과 같습니다.
{
"id": 70393,
"date": "2020-03-07T18:43:47",
"date_gmt": "2020-03-07T10:43:47",
"guid": {
"rendered": "https://www.crifan.com/files/pic/uploads/2020/03/f6956c30ef0b475fa2b99c2f49622e35.png",
"raw": "https://www.crifan.com/files/pic/uploads/2020/03/f6956c30ef0b475fa2b99c2f49622e35.png"
},
...
자세한 것은, 제 (중국어) 투고를 참조해 주세요.「 Python 」 word Word Press api REST API 」
로컬 이미지 또는 url에서 WordPress로 이미지를 업로드하기 위한 작업 코드입니다.누군가 유용하게 써주길 바래
import requests, json, os, base64
def wp_upload_image(domain, user, app_pass, imgPath):
# imgPath can be local image path or can be url
url = 'https://'+ domain + '/wp-json/wp/v2/media'
filename = imgPath.split('/')[-1] if len(imgPath.split('/')[-1])>1 else imgPath.split('\\')[-1]
extension = imgPath[imgPath.rfind('.')+1 : len(imgPath)]
if imgPath.find('http') == -1:
try: data = open(imgPath, 'rb').read()
except:
print('image local path not exits')
return None
else:
rs = requests.get(imgPath)
if rs.status_code == 200:
data = rs.content
else:
print('url get request failed')
return None
headers = { "Content-Disposition": f"attachment; filename={filename}" , "Content-Type": str("image/" + extension)}
rs = requests.post(url, auth=(user, app_pass), headers=headers, data=data)
print(rs)
return (rs.json()['source_url'], rs.json()['id'])
import base64
import os
import requests
def rest_image_upload(image_path):
message = '<user_name>' + ":" + '<application password>'
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')
# print(base64_message)
data = open(image_path, 'rb').read()
file_name = os.path.basename(image_path)
res = requests.post(url='https://<example.com>/wp-json/wp/v2/media',
data=data,
headers={'Content-Type': 'image/jpg',
'Content-Disposition': 'attachment; filename=%s' % file_name,
'Authorization': 'Basic ' + base64_message})
new_dict = res.json()
new_id = new_dict.get('id')
link = new_dict.get('guid').get("rendered")
# print(new_id, link)
return new_id, link
언급URL : https://stackoverflow.com/questions/43915184/how-to-upload-images-using-wordpress-rest-api-in-python