Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

使用Pygal库可视化Python获取的API数据 #98

Open Qingquan-Li opened 6 years ago

Qingquan-Li commented 6 years ago

开发环境:


一、执行简单的 API 调用

API 调用的另一个例子:使用 Vue.js 通过 JSON 传递 API 数据


python_repos.py

# 编写一个程序,它执行API调用并处理结果

# 1. 在macOS上安装requests库:向网站请求信息以及检查返回的响应
# pip3 install requests

# 2. 在macOS上安装pyopenssl库:pip3 install pyopenssl ,不然requests.get()请求将报错(SSL验证失败、超过URL的最大重试次数,执行抛出异常"Connection refused"):
# raise SSLError(e, request=request)
# requests.exceptions.SSLError: HTTPSConnectionPool(host='api.github.com', port=443):
# Max retries exceeded with url: /search/repositories?q=language:python&sort=stars (Caused 
# by SSLError(SSLError(1, '[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645)'),))

# 3. 处理API响应:执行简单的API调用并储存应用

# 导入模块requests
import requests

# 存储API调用的URL,然后使用requests 来执行调用
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'

try:
    # 调用get() 并将URL传递给它,再将响应对象存储在变量r 中。
    r = requests.get(url)
# except requests.exceptions.ConnectionError:
except requests.exceptions.SSLError:
    print("Status code:", "Connection refused")
else:
    # 响应对象包含一个名为status_code的属性,它让我们知道请求是否成功了(状态码200表示请求成功)。
    print("Status code:", r.status_code)
    # print(r) # 打印:<Response [200]>
    # 这个API返回JSON格式的信息:使用方法json()(Requests内置的JSON解码器)将这些信息转换为一个Python字典
    # 将转换得到的字典存储在变量response_dict中
    response_dict = r.json()
    # 这里只打印字典的键key,不打印字典的值value
    # 字典的keys()函数以列表返回一个字典所有的键
    print(response_dict.keys())

# 输出如下:
# Status code: 200
# dict_keys(['total_count', 'incomplete_results', 'items'])



iterm2-terminal



二、使用 Pygal 库:生成柱形图显示 Star 数最多的 Python 项目

python_repos_pygal.py

# 使用 Pygal 可视化仓库,生成柱形图显示GitHub上Star数最多的Python项目

# 导入模块requests
import requests
# 导入模块pygal,及要应用于图表的Pygal样式类
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

# 储存API调用的URL,然后使用requests来执行调用
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'

try:
    r = requests.get(url)
except requests.exceptions.SSLError:
    print("status_code:", "Connection refused")
else:
    # 响应状态码
    print("Status code:", r.status_code)

    # 这个API返回JSON格式的信息,使用方法json()(Requests内置的JSON解码器)将这些信息转换为一个Python字典
    response_dict = r.json()

    # 研究各个仓库的信息,items是json数组,items数组中的是json对象
    repo_dicts = response_dict['items']

    # 仓库名字、star数
    names, stars = [], []
    for repo_dict in repo_dicts:
        names.append(repo_dict['name'])
        stars.append(repo_dict['stargazers_count'])

    # 可视化
    # 使用LightenStyle 类定义了一种样式,并将其基色设置为深蓝色。传递了实参base_style,以使用LightColorizedStyle类
    my_style = LS('#333366', base_style=LCS)
    # “使用Bar() 创建一个简单的条形图,并向它传递my_style。传递另外两个样式实参:让标签绕x 轴旋转45度,并隐藏了图例
    chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
    chart.title = 'Most-Starred Python Project on GitHub'
    chart.x_labels = names

    # 由于我们不需要给这个数据系列添加标签,因此添加数据时,将标签设置成了空字符串
    # 将这个图表渲染成一个SVG文件
    chart.add('', stars)
    chart.render_to_file('python_repos_pygal.svg')


因此处不能显示 SVG 图片,故上传 PNG 格式图片替代。 生成的 SVG 图片存放地址: https://github.com/FatliTalk/images/blob/master/python_repos_pygal.svg


python_repos_pygal svg