使用WordPress自動发布带有图像的文章
首先让我们尝试使用WordPress的REST API自动发布带有图片的文章。
环境サーバー側
WordPress 5.2.4
WordPress 5.2.4
クライアント側
Python 3.7.4
列出pip安装的库:
requests 版本为2.22.0
Jinja2 版本为2.10.3
事前准备 (shì在WordPress中,有几种认证方式可供选择,但本次将使用应用程序密码。
首先,在WordPress上安装Application Password插件。


クライアントの実装例首先,准备一个用于操作WordPress的模块。
"""WORDPRESSの操作"""
import json
import os
import base64
import requests
class WordPressError(Exception):
"""WordPressのエラー情報"""
def __init__(self, ctrl, status_code, reason, message):
super(WordPressError, self).__init__()
self.ctrl = ctrl
self.status_code = status_code
self.reason = reason
self.message = message
class WordPressCtrl:
"""WordPressの操作"""
def __init__(self, url, user, password):
"""初期化処理"""
self.url = url
auth_str = f"{user}:{password}"
auth_base64_bytes = base64.b64encode(auth_str.encode(encoding='utf-8'))
self.auth = auth_base64_bytes.decode(encoding='utf-8')
def check_response(self, res, success_code):
"""WordPressからの応答をチェック"""
try:
json_object = json.loads(res.content)
except ValueError as ex:
raise WordPressError(self, res.status_code, res.reason, str(ex))
if res.status_code != success_code:
raise WordPressError(self, res.status_code, res.reason, json_object['message'])
return json_object
def add_post(self, title, content, categorie_ids=[], tag_ids=[]):
"""WordPressに記事を投稿"""
headers = {
'Authorization': 'Basic ' + self.auth
}
data = {
'title': title,
'content': content,
'format': 'standard',
'categories' : categorie_ids,
'tags' : tag_ids
}
res = requests.post(f'{self.url}/wp-json/wp/v2/posts', json=data, headers=headers)
return self.check_response(res, 201)
def update_post(self, id, title, content, categorie_ids=[], tag_ids=[]):
"""WordPressの既存記事を更新"""
headers = {
'Authorization': 'Basic ' + self.auth
}
data = {
'title': title,
'content': content,
'format': 'standard',
'categories' : categorie_ids,
'tags' : tag_ids
}
res = requests.post(f'{self.url}/wp-json/wp/v2/posts/{id}', json=data, headers=headers)
return self.check_response(res, 200)
def upload_media(self, path, content_type):
"""メディアのアップロード"""
file_name = os.path.basename(path)
headers = {
'Authorization': 'Basic ' + self.auth,
'Content-Type': content_type,
'Content-Disposition' : 'attachiment; filename={filename}'.format(filename=file_name)
}
with open(path, 'rb') as media_file:
data = media_file.read()
res = requests.post(f'{self.url}/wp-json/wp/v2/media', data=data, headers=headers)
return self.check_response(res, 201)
def upload_png(self, path):
"""メディアにPNG画像を追加"""
return self.upload_media(path, 'image/png')
def upload_jpeg(self, path):
"""メディアにJPEG画像を追加"""
return self.upload_media(path, 'image/jpeg')
"""WORDPRESSの操作"""
import json
import os
import base64
import requests
class WordPressError(Exception):
"""WordPressのエラー情報"""
def __init__(self, ctrl, status_code, reason, message):
super(WordPressError, self).__init__()
self.ctrl = ctrl
self.status_code = status_code
self.reason = reason
self.message = message
class WordPressCtrl:
"""WordPressの操作"""
def __init__(self, url, user, password):
"""初期化処理"""
self.url = url
auth_str = f"{user}:{password}"
auth_base64_bytes = base64.b64encode(auth_str.encode(encoding='utf-8'))
self.auth = auth_base64_bytes.decode(encoding='utf-8')
def check_response(self, res, success_code):
"""WordPressからの応答をチェック"""
try:
json_object = json.loads(res.content)
except ValueError as ex:
raise WordPressError(self, res.status_code, res.reason, str(ex))
if res.status_code != success_code:
raise WordPressError(self, res.status_code, res.reason, json_object['message'])
return json_object
def add_post(self, title, content, categorie_ids=[], tag_ids=[]):
"""WordPressに記事を投稿"""
headers = {
'Authorization': 'Basic ' + self.auth
}
data = {
'title': title,
'content': content,
'format': 'standard',
'categories' : categorie_ids,
'tags' : tag_ids
}
res = requests.post(f'{self.url}/wp-json/wp/v2/posts', json=data, headers=headers)
return self.check_response(res, 201)
def update_post(self, id, title, content, categorie_ids=[], tag_ids=[]):
"""WordPressの既存記事を更新"""
headers = {
'Authorization': 'Basic ' + self.auth
}
data = {
'title': title,
'content': content,
'format': 'standard',
'categories' : categorie_ids,
'tags' : tag_ids
}
res = requests.post(f'{self.url}/wp-json/wp/v2/posts/{id}', json=data, headers=headers)
return self.check_response(res, 200)
def upload_media(self, path, content_type):
"""メディアのアップロード"""
file_name = os.path.basename(path)
headers = {
'Authorization': 'Basic ' + self.auth,
'Content-Type': content_type,
'Content-Disposition' : 'attachiment; filename={filename}'.format(filename=file_name)
}
with open(path, 'rb') as media_file:
data = media_file.read()
res = requests.post(f'{self.url}/wp-json/wp/v2/media', data=data, headers=headers)
return self.check_response(res, 201)
def upload_png(self, path):
"""メディアにPNG画像を追加"""
return self.upload_media(path, 'image/png')
def upload_jpeg(self, path):
"""メディアにJPEG画像を追加"""
return self.upload_media(path, 'image/jpeg')
接下来,以下是一个示例,展示如何在WordPress中上传图片并添加文章。
请在WordPressCtrl中指定WordPress的URL、用户名和之前准备好的密码。
from jinja2 import Template
from wordpress_ctrl import WordPressCtrl,WordPressError
data = {
'data_list' : [
{
'name': '阿多田太郎',
'age' : 15,
'image_path' : 'test1.png'
},
{
'name': 'アロハ太郎',
'age' : 34,
'image_path' : 'test2.png'
}
]
}
wpctrl = WordPressCtrl('https://ワードプレスのURL', 'testuser', 'APIキー')
# 画像のアップロード
for item in data['data_list']:
try:
wpres = wpctrl.upload_png(item['image_path'])
item['img_url'] = wpres['source_url']
except WordPressError as ex:
print(ex.status_code, ex.reason, ex.message)
html = """
<h2>結果</h2>
<table border=1>
<tr>
<th>名前</th>
<th>年齢</th>
<th>画像</th>
</tr>
{% for item in data_list %}
<tr>
<td>{{ item.name | e}}</td>
<td>{{ item.age | e}}</td>
<td><img src="{{ item.img_url | e}}" width=150/></td>
</tr>
{% endfor %}
</table>
"""
try:
# 新規投稿
wpres = wpctrl.add_post('タイトル', Template(html).render(data), [1], [3])
print(wpres['id'])
# 既存投稿の更新
wpres = wpctrl.update_post(wpres['id'], 'タイトル(更新)', Template(html).render(data), [1,2], [3,4])
print(wpres['id'], wpres['title'])
except WordPressError as ex:
print(ex.status_code, ex.reason, ex.message)



请参考以下内容:
-
認証 WP REST API
- 認証 WP REST API
-
- 投稿 WP REST API
-
- How to upload images using wordpress REST api in python?
-
- Application Password
- Template Designer Documentation