我尝试通过以下代码使用 python 请求和 rest api 将帖子发布到 WordPress 博客:
auth = 'Basic ' + str(base64.b64encode(b'admin:123456'), 'utf-8')
headers = {'Authorization': auth}
body = {'title': 'Hello World'}
r = requests.post('wp-json/wp/v2/posts', headers=headers, data=body)
总是出现 401 错误:
>>> r.text
'{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}'
我很确定帐户 admin 和密码是正确的并且具有管理员角色,我错过了什么吗?
请您参考如下方法:
我能解决这个问题
我在我的 wordpress 上安装并激活了这个插件 https://wordpress.org/plugins/application-passwords/
按照那里的帮助文本并为您的用户 ID 创建密码字符串 - 假设它是 mypassword123
现在在您的终端上执行此操作 “管理员:我的密码123” | base64
您将获得一个新密码 - 例如 pwdabc123
- 代码看起来像
url_srcdest = "http://example.com/wp-json/wp/v2/pages/"
headers = {'Content-Type': 'application/json',
'Authorization': 'Basic pwdabc123',
'Username': '<your username>',
'Password':'pwdabc123'}
data = \
{
"title":"Testing via API via Python",
"content":"tEST CONTENT OF THE THIS TEST PAGE via PYTHON",
"status": "publish"
}
response = requests.post(url_srcdest, data=json.dumps(data), headers=headers)
