使用API
使用Web API
Web API是网站的一部分,用于与使用非常具体的URL请求特定信息的程序交互。这种请求称为API调用。
请求的数据将以易于处理的格式(JSON或CSV等)返回。依赖于外部数据源的大多数应用程序都依赖于API调用,如集成社交媒体网站的应用程序。
使用API调用请求数据
GitHub的API让你能够通过API调用来请求各种信息。
在浏览器中输入如下地址:
http://api.github.com/search/repositories?q=language:python&sort=stars
这个吊用返回GitHub当前托管了多少个Python项目,还有有关最受喜欢的Python仓库的信息。
第一部分:http://api.github.com/
将请求发送到GitHub网站中响应API调用的部分;
第二部分:search/repositories
让API搜索GitHub上所有的仓库。
第三部分:repositories
后的问号指出我们要传递一个实参。q
表示查询,而等号让我们能够开始指定查询(q=
)。通过使用language:python
指出我们只想获取Python的仓库的信息。最后,(&sort=stars
)指定将项目按其所获得的星级进行排序。
返回:
{
"total_count": 2371024,
"incomplete_results": false,
"items": [
{
"id": 21289110,
"name": "awesome-python",
"full_name": "vinta/awesome-python",
--snip--
截取了开头的一部分。
安装requests
requests包让Python程序能够轻松地向网站请求信息以及检查返回的响应。
执行命令
pip install --user requests
处理API响应
python_repos.py
import requests
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code: " + str(r.status_code))
response_dict = r.json()
print(response_dict.keys())
输出:
Status code: 200
dict_keys(['items', 'incomplete_results', 'total_count'])
状态码为200表示请求成功。响应字典包含三个键:'items'
、'incomplete_results'
和'total_count'
。
注:像这样简单地调用应该会返回完整的结果集,因此可以完全忽略与'incomplete_results'
相关联的值。但执行更复杂的API调用时,程序应检查这个值。
处理响应字典
python_repos.py
import requests
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code: " + str(r.status_code))
response_dict = r.json()
repo_dicts = response_dict['items']
# 研究第一个仓库
repo_dict = repo_dicts[0]
for key in sorted(repo_dict.keys()):
print(key)
输出:
Status code: 200
archive_url
archived
assignees_url
blobs_url
branches_url
--snip--
trees_url
updated_at
url
watchers
watchers_count
提取repo_dict
中的一些键相关联的值:
python_repos.py
import requests
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code: " + str(r.status_code) + '\n')
response_dict = r.json()
repo_dicts = response_dict['items']
# 研究第一个仓库
repo_dict = repo_dicts[0]
print("Name: ", repo_dict['name'])
print("Owner: ", repo_dict['owner']['login'])
print("Stars: ", 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'])
输出:
Status code: 200
Name: awesome-python
Owner: vinta
Stars: 45642
Repository: https://github.com/vinta/awesome-python
Created: 2014-06-27T21:00:06Z
Updated: 2018-02-22T05:35:49Z
Description: A curated list of awesome Python frameworks, libraries, software and resources
概述最受欢迎的仓库
import requests
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code: " + str(r.status_code) + '\n')
response_dict = r.json()
repo_dicts = response_dict['items']
for num in range(3):
for repo_dict in repo_dicts:
print("Name: ", repo_dict['name'])
print("Owner: ", repo_dict['owner']['login'])
print("Stars: ", 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'])
输出和上限差不多,不写了。
监视API的速率限制
大多数的API都存在速率限制,即你在特定时间内可执行的请求数存在限制。要获悉你是否接近了GitHub的限制,在浏览器中输入:
http://api.github.com/rate_limit
输出:
{
"resources": {
"core": {
"limit": 60,
"remaining": 60,
"reset": 1519293922
},
"search": {
"limit": 10,
"remaining": 10,
"reset": 1519290382
},
"graphql": {
"limit": 0,
"remaining": 0,
"reset": 1519293922
}
},
"rate": {
"limit": 60,
"remaining": 60,
"reset": 1519293922
}
}
看"search"
项,限制为每分钟10次,在当前的这一分钟,还可以进行10次请求。reset
值指的是配额将要重置的Unix事件或新纪元时间
(1970年1月1日午夜后多少秒)。用完配额后,将收到一条简单的响应,由此知道已到达API极限。之后必须等待重新配额。
使用Pygal可视化仓库
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
import requests
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code: " + str(r.status_code) + '\n')
response_dict = r.json()
repo_dicts = response_dict['items']
names, stars = [], []
for repo_dict in repo_dicts:
# 获取每个项目的名称以及星数
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
# 设置风格
my_style = LS('#FF0000', base_style=LCS)
# 创建条形图,使x轴标签旋转45度,隐藏图例
chart = pygal.Bar(x_label_rotation=45, show_legend=False, style=my_style)
chart.title = 'Most popular Python projects on GitHub'
chart.x_labels = names
# 不需要给这个数据系列添加标签,所以为空字符
chart.add('', stars)
chart.render_to_file('python_repos.svg')
输出:
依然是漂亮的红色。
改进Pygal图表
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
import requests
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code: " + str(r.status_code) + '\n')
response_dict = r.json()
repo_dicts = response_dict['items']
names, stars = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
my_style = LS('#FF0000', base_style=LCS)
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.width = 800
# 图表标题、主标签和副标签的的字号
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
# 将较长的项目名(标签名)缩短为15个字符
my_config.truncate_label = 15
# 隐藏图表中的水平线
my_config.show_y_guides = False
# 创建条形图的时候就将设置直接导入
chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most popular Python projects on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')
输出:
添加自定义工具提示
在Pygal中,将鼠标指向条形将显示它表示的信息,这通常称为工具提示。在这个示例中,当前显示的是项目中获得了多少个星。下面来创建一个自定义工具提示,以同时显示项目的描述。
--snip--
repo_dicts = response_dict['items']
names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
}
plot_dicts.append(plot_dict)
--snip--
chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most popular Python projects on GitHub'
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
Pygal根据与键'value'
相关的值决定条形的高度,并使用与'label'
相关联的字符串创建工具栏提示。
但是,它给我报错了:
Traceback (most recent call last):
File "D:/PyCharm 2017.1.5/项目/python_repos.py", line 38, in <module>
chart.render_to_file('python_repos.svg')
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\graph\public.py", line 114, in render_to_file
f.write(self.render(is_unicode=True, **kwargs))
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\graph\public.py", line 52, in render
self.setup(**kwargs)
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\graph\base.py", line 217, in setup
self._draw()
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\graph\graph.py", line 933, in _draw
self._plot()
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\graph\bar.py", line 146, in _plot
self.bar(serie)
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\graph\bar.py", line 116, in bar
metadata)
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\util.py", line 233, in decorate
metadata['label'])
File "C:\Users\TR\AppData\Roaming\Python\Python35\site-packages\pygal\_compat.py", line 61, in to_unicode
return string.decode('utf-8')
AttributeError: 'NoneType' object has no attribute 'decode'
错误是最后一行chart.render_to_file('python_repos.svg')
那里。
看最后一句AttributeError: 'NoneType' object has no attribute 'decode'
,直接翻译过来就是“无类型的对象没有属性能“解码”,所以,大概是某处的description
为空,导致了此异常。
那,改呗:
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
if repo_dict['description']:
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
}
else:
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': ' ',
}
plot_dicts.append(plot_dict)
输出:
D:\Python\python.exe "D:/PyCharm 2017.1.5/项目/python_repos.py"
Status code: 200
Process finished with exit code 0
在图表中添加链接
Pygal允许你将图表中的每个条形用作网站的链接,只需在每个项目创建的字典中,添加一个键'xlink'
。
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
'xlink': repo_dict['html_url']
}
关于链接这部分想要深入学习可以看这里,官方文档,作为一个官方文档,讲的非常的细致,每一个知识点都有例子,生动形象,而且里面的英文也不算难,实在不行查查就好了,加油。