Python学习笔记:使用API

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 21:21:58 2020

@author: 86159
"""
# use #%% to create cells;Run current cell(ctrl+enter)
#%%
#使用API
#   https://api.github.com/search/repositories?q=language:python&sort=stars
#  https://api.github.com/ 将请求发生到GitHub网站中响应API调用的部分
#  search/repositories 让API搜索GitHub上的所有仓库
#  ? 指出需要传递一个实参
#  q= q表示查询,等号让我们能够开始指定查询
#  language:python 指出只想获取主要语言为python的仓库的信息
#  &sort=stars 指定将项目按其获得的星级进行排序
#{
#"total_count": 4971219,
#  "incomplete_results": false, --表示请求是成功的(并非不完整的)
#  "items": [
#          {
#                  "id":xx,
#                  "dd":ss,
#                  },
#          {},
#          {}
#          ]
#}
#%%
#requests
import requests

#执行API调用并存储响应
url="https://api.github.com/search/repositories?q=language:python&sort=stars"
req=requests.get(url)#把响应对象存储在req中
#print(str(type(req)))
#<class 'requests.models.Response'>
print("Status code:",req.status_code)#状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=req.json()#这个api返回json格式的信息,因此使用方法json()将这些信息转换成一个python字典
#btcdata_list=json.loads(req.text)

#------------------------------处理API响应-------------------------------------
##处理结果
#print(response_dict.keys())
##dict_keys(['total_count', 'incomplete_results', 'items'])
##简单的调用应该会返回完整的结果集,因此可以忽略与incomplete_results相关联的值
##但执行更复杂的api调用时,程序应检查这个值

#------------------------------处理响应字典-------------------------------------
print("total counts:",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 repo_dict.keys():
    print(key)#键

#for index,key in enumerate(repo_dict.keys()):#返回字典中每个元素的索引+键;#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
#    print(index,key)

print("\nSelected information about first repository:")
print("Name:",repo_dict['name'])
print("Owner:",repo_dict['owner']['login'])#键owner所关联的值是字典类型:b=a['x'] c=b['y']<-->c=a['x']['y']

#------------------------------监视api的速率限制--------------------------------
#很多api要求注册获得api密钥后才能执行api调用
#https://api.github.com/rate_limit
#{
#  "resources": {
#    "core": {
#      "limit": 60,
#      "remaining": 59,
#      "reset": 1584692941
#    },
#    "search": {
#      "limit": 10,  --极限为每分钟10个请求
#      "remaining": 9, --在当前这一分钟内,还可执行9个请求
#      "reset": 1584689933 --配额将重置的Unix时间或新纪元时间
#    },
#    "graphql": {
#      "limit": 0,
#      "remaining": 0,
#      "reset": 1584693477
#    },
#    "integration_manifest": {
#      "limit": 5000,
#      "remaining": 5000,
#      "reset": 1584693477
#    },
#    "source_import": {
#      "limit": 5,
#      "remaining": 5,
#      "reset": 1584689937
#    }
#  },
#  "rate": {
#    "limit": 60,
#    "remaining": 59,
#    "reset": 1584692941
#  }
#}
#%%
#------------------------------使用Pygal可视化仓库------------------------------
import requests
import pygal
import json
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS#设置图表样式

#执行API调用并存储响应
url="https://api.github.com/search/repositories?q=language:python&sort=stars"
req=requests.get(url,verify=False)
#关闭ssl认证:verify=False

#InsecureRequestWarning
#requests.packages.urllib3.disable_warnings()

repdata=json.loads(req.text)
#for key,value in repdata.items():#键
#    print(key)

repo_items=repdata['items']#仓库信息

#for index,key in enumerate(repo_items):#显示索引 键
#    print(index,key)

names,stars=[],[]#初始化两个空列表用来存储name star
hurls=[]
for repo_item in repo_items:
    names.append(repo_item['name'])
    stars.append(repo_item['stargazers_count'])
    hurls.append(repo_item['html_url'])

#------------------------------改进前------------------------------------------
#可视化
my_style=LS('#333366',base_style=LCS)#设置图表样式

#chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart=pygal.Bar()
chart.style=my_style
chart.x_label_rotation=45
chart.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')

#------------------------------改进后------------------------------------------
#可视化
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=50#图表标题字体大小
#my_config.label_font_size=14#副标签字体大小:x轴上的项目名以及y轴上的大部分数字
#my_config.major_label_font_size=18#主标签字体大小:y轴上5000整数倍的刻度
my_config.truncate_label=10#x轴的项目名缩短为10个字符(将鼠标指向屏幕上被截短的项目名,将显示完整的项目名)
my_config.show_y_guides=False#隐藏图表中的水平线
my_config.width=1000#自定义宽度,让图表更充分地利用浏览器中的可用空间
#画图
chart=pygal.Bar(my_config,style=my_style)#把my_config作为第一个实参,从而通过一个实参传递了所有的配置设置;可以通过my_config做任意数量的样式和配置修改
chart.title='Most-Starred Python Projects on GitHub'
chart.x_labels=names

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

#------------------------------添加自定义工具提示-------------------------------
#在pygal中,将鼠标指向条形将显示它表示的信息,这通常称为工具提示
#向add传递一个字典列表,而不是值列表
#pygal根据与键'value'相关联的数字来确定条形的高度
#与'label'相关联的字符串给条形创建工具提示
dscps=[]
for i in range(len(names)):
    dscp={}#放在循环内,每次初始化为一个空字典,然后用下面的语句添加键值对;初始化放在循环外则是修改键值对
    dscp['value']=stars[i]
    dscp['label']="Description of "+names[i]
    #dscp={'value':stars[i],'label':"Description of "+names[i]}#初始化一个字典并赋值

    dscps.append(dscp)


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('',dscps)#dscps为列表,其中的元素是字典
chart.render_to_file('bar_description.svg')#图表会存储在右上方的位置
#------------------------------在图表中添加可单击的链接-------------------------
#pygal根据与键'xlink'相关联的URL将每个条形都转换为活跃的链接
dscps=[]
for i in range(len(names)):
    dscp={}
    dscp['value']=stars[i]
    dscp['label']="Description of "+names[i]
    dscp['xlink']=hurls[i]

    dscps.append(dscp)

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('',dscps)#dscps为列表,其中的元素是字典
chart.render_to_file('bar_description_url.svg')

 

发布了78 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37209590/article/details/105001085