Web API 是网站的一部分, 用于与使用非常具体的URL请求特定信息的程序交互. 下面通访问github API来演示怎么使用python调用API.
# -i https://pypi.mirrors.ustc.edu.cn/simple/ 临时访问国内镜像源
pip3 install --user requests -i https://pypi.mirrors.ustc.edu.cn/simple/
尝试访问github API
在浏览器中输入https://api.github.com/rate_limit
, 看到下面的响应:
{
"resources": {
"core": {
"limit": 60,
"remaining": 60,
"reset": 1603881990,
"used": 0
},
"graphql": {
"limit": 0,
"remaining": 0,
"reset": 1603881990,
"used": 0
},
"integration_manifest": {
"limit": 5000,
"remaining": 5000,
"reset": 1603881990,
"used": 0
},
"search": {
"limit": 10,
"remaining": 10,
"reset": 1603878450,
"used": 0
}
},
"rate": {
"limit": 60,
"remaining": 60,
"reset": 1603881990,
"used": 0
}
}
从响应的json中可以看出search每分钟可以调用10次.
下面具体测试search的API(查询python的仓库信息):
https://api.github.com/search/repositories?q=language:python&sort=stars
先展示pygal的自定义工具提示, 后面代码会用到
bar_descriptions.py
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 自定义工具提示
# '#333366' 深蓝色
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Python Projects'
chart.x_labels = ['httpie', 'django', 'flask']
plot_dicts = [
{'value': 16101, 'label': 'Description of httpie'},
{'value': 15028, 'label': 'Description of django'},
{'value': 14798, 'label': 'Description of flask'}
]
chart.add('', plot_dicts)
chart.render_to_file('bar_descriptions.svg')
生成的图表(在浏览器中打开bar_descriptions.svg文件):
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NB7orFcO-1637679384959)(/upload/2020/10/%E6%88%AA%E5%B1%8F2020-10-29%20%E4%B8%8B%E5%8D%881.49.56-6e4c707ca8dd43b29646543cb496bd9a.png)]
下面具体展示GitHub API的调用
python_repos.py
import requests
import pygal
import json
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
# 因为访问github api有访问次数限制,访问成功我生成一个 github_python_repositories.json 文件,如果达到限制次数,就读取本地的文件
filename = 'github_python_repositories.json'
try:
r = requests.get(url)
print("Status code: ", r.status_code)
if r.status_code == 403:
raise Exception('达到访问限制次数,一分钟后再试!')
# 将API响应存储在一个变量中
response_dict = r.json()
except Exception as err:
print('访问github api 异常:', err)
with open(filename) as f:
response_dict = json.load(f)
else:
# 将数据写入文件
with open(filename, 'w') as f:
f.write(r.text)
print("Total Repositories: ", response_dict['total_count'])
# 搜索有关仓库的信息
# repo_dicts 列表
repo_dicts = response_dict['items']
print("Repositories returned: ", len(repo_dicts))
names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
# description 可能为空
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': str(repo_dict['description']),
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)
# 可视化
# '#333366' 深蓝色
my_style = LS('#333366', base_style=LCS)
my_config = pygal.Config()
# x_label_rotation=45 让标签让x轴旋转45度
my_config.x_label_rotation = 45
# show_legend=False 隐藏图例
my_config.show_legend = False
# 将较长的项目名缩短为15个字符
my_config.truncate_label = 15
# 隐藏图表中的水平线
my_config.show_y_guides = False
# 设置宽度
my_config.width = 1000
chart = pygal.Bar(my_config, style=my_style)
chart.title = 'GitHub上更多的Star的python工程'
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
# 研究第一个仓库
# repo_dict = repo_dicts[0]
# print("\nkeys: ", len(repo_dict))
# for key in sorted(repo_dict.keys()):
# print(key)
# print("\n显示第一个仓库的信息:")
# print('Name:', repo_dict['name'])
# print('Owner:', repo_dict['owner']['login'])
# print('Star:', repo_dict['stargazers_count'])
# print('Repository:', repo_dict['html_url'])
# print('Created:', repo_dict['created_at'])
# print('Updated:', repo_dict['updated_at'])
# print('Description:', repo_dict['description'])
# 处理结果
# print(response_dict.keys())
生成的图表(在浏览器中打开python_repos.svg):
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tUBVQEqL-1637679384960)(/upload/2020/10/%E6%88%AA%E5%B1%8F2020-10-29%20%E4%B8%8B%E5%8D%881.52.16-9eee03b90ef445918e8deeafde6fc0b3.png)]
代码:
bar_descriptions.py
bar_descriptions.py
生成的文件:
bar_descriptions.svg
python_repos.svg
github_python_repositories.json
Python3 目录