使用Python请求和REST API发布WordPress Post

时间:2017-01-08 12:33:43

标签: python wordpress rest

我尝试使用python请求将帖子发布到WordPress博客,并通过以下代码发布api:

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}}'

我非常确定帐户管理员和密码是否正确且具有管理员角色,我是否遗漏了什么?

3 个答案:

答案 0 :(得分:2)

我能够解决这个问题

一个。我安装了&在我的wordpress上激活了这个插件 https://wordpress.org/plugins/application-passwords/

B中。按照那里的帮助文本为您的用户ID创建密码字符串 - 假设它是mypassword123

℃。现在在您的终端上执行此操作 “admin:mypassword123”| BASE64

您将获得一个新密码 - 比如说pwdabc123

d。代码看起来像

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)

答案 1 :(得分:2)

你错过了:

  • auth 您的jwt token不是 base64 encode token
    • jwt token 来自 POST /wp-json/jwt-auth/v1/token

如何获得jwt token

先决条件

安装jwt插件

安装并启用 WordPress 插件:

wordpress 服务器启用 jwt 授权

例如,我的 wordpress 服务器是:CentOS

  1. 在 wordpress 根文件夹中编辑 .htaccess

添加:

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
  1. 编辑wp-config.php

添加:

define('JWT_AUTH_SECRET_KEY', 'anyValueIsOk');
  • anyValueIsOk:改成你的,任何值都可以
    • 不要告诉别人,^_^
  • 编辑php文件后记住service php-fpm restart

POST /wp-json/jwt-auth/v1/token 生成 jwt 令牌

调用REST api生成jwt token

POST https://www.yourWebsite.com/wp-json/jwt-auth/v1/token

{
    "username": "wordpress_username",
    "password": "wordpress_password"
}
  • wordpress_username:这是你的admin
  • wordpress_password:这是你的123456

回复:

{
    "token": "eyJ0eXAiOxxxxxxxxxxxxHYBhtuzc",
    "user_email": "xxx@yyy.com",
    "user_nicename": "xxx",
    "user_display_name": "xxx"
}
  • eyJ0eXAiOxxxxxxxxxxxxHYBhtuzc:是jwt 令牌,这正是您所需要的

[可选] 验证令牌是否有效

POST https://www.crifan.com/wp-json/jwt-auth/v1/token/validate

headers:
Authorization: Bearer eyJ0eXAiOxxxxxxxxxxxxHYBhtuzc

回复:

{
    "code": "jwt_auth_valid_token",
    "data": {
        "status": 200
    }
}

另外:使用python调用wordpress REST api来创建帖子

代码:

import requests

your_jwt_token = "xxx"

curHeaders = {
    "Authorization": "Bearer %s" % your_jwt_token,
    "Content-Type": "application/json",
    "Accept": "application/json",
}

categoryIdList = []
tagIdList = []

if categoryNameList:
    # ['Mac']
    categoryIdList = self.getTaxonomyIdList(categoryNameList, taxonomy="category")
    # category nameList=['Mac'] -> taxonomyIdList=[1374]

if tagNameList:
    # ['切换', 'GPU', 'pmset', '显卡模式']
    tagIdList = self.getTaxonomyIdList(tagNameList, taxonomy="post_tag")
    # post_tag nameList=['切换', 'GPU', 'pmset', '显卡模式'] -> taxonomyIdList=[1367, 13224, 13225, 13226]

postDict = {
    "title": title, # '【记录】Mac中用pmset设置GPU显卡切换模式'
    "content": content, # '<div>\n  折腾:\n </div>\n <div>\n  【已解决】Mac Pro 2018款发热量大很烫非常烫\n </div>\n <div>\n  期间,...performance graphic cards\n    </li>\n   </ul>\n  </ul>\n </ul>\n <div>\n  <br/>\n </div>'
    # "date_gmt": dateStr,
    "date": dateStr, # '2020-08-17T10:16:34'
    "slug": slug, # 'on_mac_pmset_is_used_set_gpu_graphics_card_switching_mode'
    "status": status, # 'draft'
    "format": postFormat, # 'standard'
    "categories": categoryIdList, # [1374]
    "tags": tagIdList, # [1367, 13224, 13225, 13226]
    # TODO: featured_media, excerpt
}

yourHost = 'https://www.crifan.com'
createPostUrl = yourHost + "/wp-json/wp/v2/posts" # 'https://www.crifan.com/wp-json/wp/v2/posts'

resp = requests.post(
    createPostUrl,
    # proxies=self.requestsProxies,
    headers=curHeaders,
    # data=json.dumps(postDict),
    json=postDict, # internal auto do json.dumps
)

响应示例:

{
  "id": 70410,
  "date": "2020-02-27T21:11:49",
  "date_gmt": "2020-02-27T13:11:49",
  "guid": {
      "rendered": "https://www.crifan.com/?p=70410",
      "raw": "https://www.crifan.com/?p=70410"
  },
  "modified": "2020-02-27T21:11:49",
  "modified_gmt": "2020-02-27T13:11:49",
  "password": "",
  "slug": "mac_pip_change_source_server_to_spped_up_download",
  "status": "draft",
  "type": "post",
  "link": "https://www.crifan.com/?p=70410",
  "title": {
      'raw": "【已解决】Mac中给pip更换源以加速下载",
      "rendered": "【已解决】Mac中给pip更换源以加速下载"
  },
  "content": {
      ...
  }
}

注意:


更多细节请参考我的中文帖子:

答案 2 :(得分:0)

我只使用here中所述的requests以及应用程序密码:

import requests
r = requests.get('https://example-wp.com/wp-json/', auth=('username', 'APPLICATIONPASSWORD'))
r.status_code