右侧显示信息
广告位 后台主题配置管理

凯发k8一触即发-凯发k8国际 > zblog专区 正文

wordpress使用rest api新建、更新、删除文章教程(python代码)zblog专区柠檬文苑-凯发k8一触即发-凯发k8国际

w227 2023-03-13 11:05:56 zblog专区 824 ℃
广告位 后台主题配置管理

转载自https://www.vpsgo.com/wordpress-manage-posts-with-rest-api-using-python.html

之前在介绍wordpress应用程序密码(application passwords)时vps go有说过这个程序密码的一大用处就是授权rest api,今天就给大家介绍下wordpress rest api的用法,利用python来新建、更新、删除文章。

一、申请

应用程序密码不是登录密码,详细的介绍与申请方式可以参考之前vps go的分享:

《wordpress应用程序密码(application passwords)设置教程》

二、使用rest api管理博客文章

这里直接分享python版本的代码了,其他的代码可以在这个基础上自行修改。

首先需要导入需要的包:

import requests
import json
import base64

可以通过这个代码查看是否成功授权,reponse是否正确:

url = "https://example.com/wp-json/wp/v2/posts" 
user = "your-username"
password = "your-application-password"
credentials = user   ':'   password
token = base64.b64encode(credentials.encode())
header = {'authorization': 'basic '   token.decode('utf-8')}
response = requests.get(url , headers=header)
print(response)

其中:

  • example.com是你自己的域名

  • user是你的登录名

  • password是你刚才申请的应用程序密码

利用rest api新建文章代码:

url = "https://example.com/wp-json/wp/v2/post"
user = "your-username"
password = "your-application-password"
credentials = user   ':'   password
token = base64.b64encode(credentials.encode())
header = {'authorization': 'basic '   token.decode('utf-8')}
post = {
'title' : 'hello world',
'status' : 'publish',
'content' : 'this is my first post created using rest api',
'categories': 5, // category id
'date' : '2020-01-05t10:00:00'
}
response = requests.post(url , headers=header, json=post)
print(response)

利用rest api更新文章代码:

url = "https://example.com/wp-json/wp/v2/posts" 
postid = 1
user = "your-username"
password = "your-application-password"
credentials = user   ':'   password
token = base64.b64encode(credentials.encode())
header = {'authorization': 'basic '   token.decode('utf-8')}
post = {
'title' : 'hello world updated',
'content' : 'this is my first post created using rest api updated'
}
response = requests.post(url   postid , headers=header, json=post)
print(response)

利用rest api删除文章代码:

url = "https://example.com/wp-json/wp/v2/posts" 
user = "your-username"
password = "your-application-password"
credentials = user   ':'   password
token = base64.b64encode(credentials.encode())
header = {'authorization': 'basic '   token.decode('utf-8')}
response = requests.delete(url   postid , headers=header)
print(response)

以上就是wordpress rest api的使用方法了,除了这个接口外,wordpress还有xmlrpc接口,自行百度

联系凯发k8一触即发
付费后若不能复制,请刷新页面重试。 如有问题,再加客服微信。 工作日上午8:30-11:30 14:30-17:30
免费复制
微信扫码领取验证码
注:需在公众号回复"验证码"
输入验证码后可以免费复制
付费复制
付费30天内免费复制

价格:2.99元

支付宝支付
扫一扫,支付¥2.99

正在加载二维码...

支付完成后,请等待10秒左右,请勿关闭此页
请在这里放置你的在线分享代码
最近发表
标签列表
最新留言
网站地图