包含两个文件,先附上源码,后续整理一下思路。
更新!!!
我把api请求的数据整合到了文本文件中,这样就不需要每次都进行api请求了!
1.get_repo.py
# get_repo.py get information from api
import requests
import json
# 执行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() # 将返回的json格式通过json方法转化成字典
print("Total repositories:", response_dict['total_count'])
# 将信息写入
with open("result.txt", "w") as fp:
fp.write(json.dumps(response_dict,indent=4))
2.analyze_repo.py
# analyze_repo.py analyzing data from result.txt
import pygal
import json
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 研究有关仓库的信息
# 从文本文件的json格式里面加载成字典
with open("result.txt", "r") as fp:
response_dict = json.load(fp)
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'])
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': str(repo_dict['description']),
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)
"""
# 打印返回每个项目的信息
for repo_dict in repo_dicts:
print("\nSelected information about first repository:")
print("Name:", repo_dict['name'])
print("Owner:", repo_dict['owner']['login'])
print("Stars:", repo_dict['stargazers_count'])
print("Created:", repo_dict['created_at'])
print("Updated:", repo_dict['updated_at'])
print("Description:", repo_dict['description'])
"""
"""
# 研究第一个仓库
repo_dict = repo_dicts[0]
print("\nKeys:",len(repo_dict))
for key in sorted(repo_dict.keys()):
print(key)
"""
# https://api.github.com/rate_limit 查找api限额
# 可视化
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.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000
chart = pygal.Bar(my_config, style=my_style)
chart.title = "Most-Starred Python Projects on Github"
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
3.test_python_repos.py
# test_python_repos.py
import unittest
import python_repos
class TestPythonRepos(unittest.TestCase):
def test1(self):
result = python_repos.r.status_code
# 判断请求状态码是否正确
self.assertEqual(result, 200, "请求码错误")
def test2(self):
result = len(python_repos.repo_dicts)
# 比较请求数量是否超过需要数量
self.assertLess(result, 33, "超过所期望的数据数量")
def test3(self):
result = python_repos.repo_dict.keys()
self.assertIn("name",result,"没有包含所期望的条目")
if __name__ == "__main__":
# 执行类中所有以test开头的函数,不需要实例化
unittest.main()
这里是第一上传github的地址哈哈!地址
可以自己尝试做做其他的图,可以当python一个小作业。