Python从入门到实践,总结笔记7:API

使用web的API:

GitHub(https://github.com/ )的名字源自Git,Git是一个分布式版本控制系统,让程序员团队能够协作开发项目。Git帮助大家管理为项目所做的工作,避免一个人所做的修改影响其他人所做的修改。你在项目中实现新功能时,Git将跟踪你对每个文件所做的修改。确定代码可行后,你提交所做的修改,而Git将记录项目最新的状态。如果你犯了错,想撤销所做的修改,可轻松地返回以前的任何可行状态(要更深入地了解如何使用Git进行版本控制,请参阅附录D)。GitHub上的项目都存储在仓库中,后者包含与项目相关联的一切:代码、项目参与者的信息、问题或bug报告。

requests包让Python程序能够轻松地向网站请求信,息以及检查返回的响应;

它执行API调用并处理结果,找出GitHub上星级最高的Python项目;

响应对象包含一个名为status_code 的属性,它让我们知道请求是否成功了;

这个API返回JSON格式的信息,因此我们使用方法json() 将这些信息转换为一个Python字典;

我们创建了两个空列表,用于存储将包含在图表中的信息。我们需要每个项目的名称,用于给条形加上标签,我们还需要知道项目获得了多少个星,用于确定条形的高度。在循环中,我们将项目的名称和获得的星数附加到这些列表的末尾;

使用LightenStyle 类(别名LS )定义了一种样式,并将其基色设置为深蓝色;

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

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

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

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'],
    }
    plot_dicts.append(plot_dict)


my_style = LS('#333366', base_style=LCS)

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
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000

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('', plot_dicts)
chart.render_to_file('python_repos.svg')

在Pygal中,将鼠标指向条形将显示它表示的信息,这通常称为工具提示 。在这个示例中,当前显示的是项目获得了多少个星。下面来创建一个自定义工具提示,以同时显示项目的描述。

import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

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')

猜你喜欢

转载自blog.csdn.net/weixin_42717395/article/details/88917300