我有一个网站是用hugo生成的静态页面,里面是翻译的2000多篇文章,越来越臃肿,更新起来耗时越来越长,今天决定写个脚本把这个网站迁移成wordpress的。生成文章的思路很明确:
1、直接操作wordpress数据库
2、使用restful api
考虑之后决定使用restful api,好事果然多磨,在调用创建文章的API的时候出现如下报错:
{ "code":"rest_cannot_create", "message":"Sorry, you are not allowed to create posts as this user.", "data":{ "status":401 } }
一番Google终于找到了解决方法,详细步骤记录如下:
1、安装Basic-Auth插件
这是一个非常老的插件,最后一次更新是5年前,给wordpress添加了基础的权限认证,官方的说明中指出每次请求的时候都会发送用户名和密码,因此最好是在SSL连接中使用,否则非常不安全。Basic Auth的Github地址在这里。
首先,点击下图中的Download ZIP下载插件
然后,在wordpress后台管理中依次点击插件->安装插件->上传插件->Choose file
,选择刚刚下载的Zip插件安装包,点击现在安装
。
2、配置Nginx支持Authorization字段
Basic-Auth的权限校验使用的在请求头中添加Authorization字段的方式。如果使用的是Nginx需要配置让Nginx把这个字段传给PHP解释器,在location ~* \.php$ {} 代码块中添加如下参数:
fastcgi_pass_header Authorization;
3、使用Basic-Auth调用创建文章的Restful API
Authorization需要设置在请求头中,值是
Basic YWRtaW46MTIzNDU2
后面这一串代码是’用户名:密码
‘经过base64编码后的字符串,比如用户名是admin
,密码是123456
,则生成的token是YWRtaW46MTIzNDU2
这里用python举例,完整的请求头和代码如下:
import requests import json def create_article(): url = 'http://xxx.com/wp-json/wp/v2/posts' headers = { "Content-Type": "application/json; charset=UTF-8", "Authorization": 'Basic YWRtaW46MTIzNDU2' } article = { 'slug': '1', 'status': 'publish', 'title': 'test', 'content': 'this is a test article', 'excerpt': 'this is excerpt', 'format': 'standard', 'author': 1 } res = requests.post(url=url, data=json.dumps(article), headers=headers) print(res.text) create_article()
欢迎转载,请注明出处:闪电树熊 » WordPress使用Restful API创建文章,报错you are not allowed to create posts as this user解决方法