若谷学院
互联网公司技术架构分享

7.WordPress:如何调用WordPress Rest API (By Basic Auth)

准备WordPress API库

# 安装插件,或者下载插件把源码放入自己的项目中:
https://github.com/derwentx/wp-api-python
 
OAuth 2.0经过测试未能成功调用API,使用basic auth可以访问Wordpress API。
 

获取所有用户

from wordpress import API
api = API(
            url=”https://www.ruoguschool.com“,
            consumer_key=”XXXXXXXXXXXX”,
            consumer_secret=”XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”,
            api=”wp-json”,
            version=’wp/v2′,
            wp_user=config.WP_USERNAME,
            wp_pass=config.WP_PASSWORD,
            basic_auth = True,
            user_auth = True,
        )
 
response = api.get(“users”)
#print(response.content)
print(response.json())
 

如何在Get请求中指定query parameters来设定分页大小?

Requests的Get请求指定page条件的方法
Read last_page and make a get request for each page in the range:
importrequests
 
r_sanfran = requests.get(“https://api.angel.co/1/tags/1664/jobs“).json()
num_pages=r_sanfran[‘last_page’]
 
forpageinrange(2,num_pages+1):
    r_sanfran = requests.get(“https://api.angel.co/1/tags/1664/jobs“,params={‘page’:page}).json()
   printr_sanfran[‘page’]
   # TODO: extract the data
 
 

例:WordPress取到所有分类标签

”’ get all categories, 指定最大单页记录条数取数据 ‘”
 
from wordpress import API
 
api = API(
            url=”https://www.ruoguschool.com“,
            consumer_key=”XXXXXXXXXXXX”,
            consumer_secret=”XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”,
            api=”wp-json”,
            version=’wp/v2′,
            wp_user=config.WP_USERNAME,
            wp_pass=config.WP_PASSWORD,
            basic_auth = True,
            user_auth = True,
        )
 
response = api.get(‘categories’, params={‘per_page’: MAX_TAG_COUNT})
 

 

全球互联网技术架构,前沿架构参考

联系我们博客/网站内容提交