美文网首页
4. Python使用API(Request)

4. Python使用API(Request)

作者: YangDxg | 来源:发表于2018-05-02 15:13 被阅读0次

1. 安装requests

$ pip install --user requests
  1. 处理API响应(找出GitHub上星际最高的Python项目):
import requests 

#执行API调用并存储响应

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code",r.status_code)

#将API响应存储在一个变量中
response_dict = r.json()

#处理结束
print(response_dict.keys())

打印结果

Status code 200
dict_keys(['total_count', 'incomplete_results', 'items'])
  1. 处理响应字典(分析最受欢迎的第一个仓库)
import requests 

#执行API调用并存储响应

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code",r.status_code)

#将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:",response_dict['total_count'])

#探索有关仓库的信息
repo_dicts = response_dict['items']
print("Repositories returned:",len(repo_dicts))

#研究第一个仓库
repo_dict = repo_dicts[0]
print("\nKeys:", len(repo_dict))
for key in sorted(repo_dict.keys()):
    print(key)

print("\nSelected information about first repository:")
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'])
  1. 监视API的速率限制

    大多数API都存在速率限制,即你在特定时间内可执行的请求数存在限制,浏览器输入网址https://api.github.com/rate_limit查看GitHub的限制
resources   
core    
limit   60
remaining   42
reset   1525228123
search  
limit   10
remaining   10
reset   1525225082
graphql 
limit   0
remaining   0
reset   1525228622
rate    
limit   60
remaining   42
reset   1525228123
  1. 使用Pygal可视化仓库
import requests 
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

#执行API调用并存储响应

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code",r.status_code)

#将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:",response_dict['total_count'])

#探索有关仓库的信息
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('#333366',base_style=LCS)
chart = pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names

chart.add('',stars)
chart.render_to_file('python_repos.svg')

使用LightenStyle类(别名LS)定义了一种样式,并将其基色设置为深蓝色。传递了实参base_style,以使用LightColorizedStyle类(别名LCS)。然后,使用 Bar()创建一个简单的条形图,并向它传递了my_style.传递了另外两个样式实参: 让标签绕x轴旋转45度(x_label_rotation=45),并隐藏了图例(show_legend=False),因为在图表中绘制一个数据系列。接下来,给图表指定了标题,并将属性x_labels设置为列表 names。

  1. 改进Pygal图表

    创建一个配置对象,其中包含传递给Bar()的所有定制
#可视化
my_style = LS('#333366',base_style=LCS)

#改进Pygal图表
#通过修改my_config的属性,可定制图标的外观
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
#图表标题、副标 签和主标签的字体大小
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
#使用 3 truncate_label将较长的项目名缩短为15个字符
my_config.truncate_label = 15
my_config.show_y_guides = False
设置自定义宽度,让图表更充分地利用浏览器中的可用空间
my_config.width =1000

chart = pygal.Bar(my_config,style=my_style)

6.添加自定义工具提示

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('python_repos.svg')
image
  1. 根据数据绘制图

    自定生成plot_dicts
import requests 
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

def description(repo_dict_json):
    description_str = repo_dict_json['description']
    if description_str:
        return description_str
    else:
        return ""

#执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code",r.status_code)

#将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:",response_dict['total_count'])

#探索有关仓库的信息
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':description(repo_dict),
    }
    plot_dicts.append(plot_dict)

#可视化
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 = names
chart.add('',plot_dicts)
chart.render_to_file('python_repos.svg')

开始plot_dict写的是

plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
}

报错:AttributeError: 'NoneType' object has no attribute 'decode',是因为有的item的description是空的,于是添加方法description对其进行判断


image
  1. 在图表中添加可单机的链接
    plot_dict = {
        'value':repo_dict['stargazers_count'],
        'label':description(repo_dict),
        'xlink': repo_dict['html_url']
    }

Pygal根据与键‘xlink’相关联的URL将每个条形都转换为活跃的链接,单机可以打开一个新的标签页

相关文章

网友评论

      本文标题:4. Python使用API(Request)

      本文链接:https://www.haomeiwen.com/subject/oprcrftx.html