2017-05-11 17 views
1

私はこれを90%稼働させていると思いますが、空の透過イメージを「アップロード」することになります。私はアップロード後に201の応答を得ます。 WPが欠落している画像を見つけたときの代理人だと思う。私はイメージを間違って渡している(つまり、コンピュータを離れない)か、私がWPの好みに正しくタグ付けしていないかどうかは分かりません。pythonでwordpress REST apiを使って画像をアップロードするには?

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での構文を理解するトラブルを抱えています。何か助けてくれてありがとう!

+0

私はそれを理解しました。 – tinyenormous

答えて

3

私はそれを理解しました!

この機能を使用すると、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) 
+0

ソリューションを投稿していただきありがとうございます。これは本当にいいですね。それはまた私のために働いた。 –

+0

Cookieベース認証(WPのデフォルト)を使用するための代替設定がありますか? – gregturn

関連する問題