python使用API

2018-09-28  本文已影响0人  梦vctor

使用API
Web应用编程接口(API)自动请求网站的特定信息而不是整个网页,再对这些信息进行可视化。即使数据瞬息万变,它呈现的信息是最新的。
1、使用Web API
Web API是网站的一部分,用于与使用非常具体的URL请求特定信息的程序交互。这种请求称为API调用。请求的数据将以易于处理的格式(如JSON或CSV)
返回。依赖于外部数据源的大多数应用程序都依赖于API调用,如集成社交媒体网站的应用程序。
1.1 Git和GitHub
Git是一个分布式版本控制系统。
1.2 使用API调用请求数据

https://api.github.com/search/repositories?q=language:python&sort=stars

https://api.github.com/:将请求发送到GitHub网站中响应API调用的部分;search/repositories:让API搜索GitHub上的所有仓库;
?:指出要传递参数;q=language:python:q表示查询,指出获取主要语言为python的仓库信息;&sort=stars:指定将项目按其获得的星级进行排序。
1.3 安装requests
pip install --user requests
1.4 处理API响应

import requests #导入模块requests

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'   #存储url
r=requests.get(url) #执行调用
print("Status code:",r.status_code) #status_code属性让我们知道请求是否成功(状态200表示请求成功)

#将API响应存储在一个变量中
response_dict=r.json()  #转化为python字典

#处理结果
print(response_dict.keys()) #打印字典中的键

输出:

Status code: 200
dict_keys(['total_count', 'incomplete_results', 'items'])

1.5 处理响应字典

import requests #导入模块requests

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=starts'  #存储url
r=requests.get(url) #执行调用
print("Status code:",r.status_code) #status_code属性让我们知道请求是否成功(状态200表示请求成功)

#将API响应存储在一个变量中
response_dict=r.json()  #转化为python字典
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)

输出:

Status code: 200
Total repositories: 3028797
Repositories returned: 30

Keys: 73
archive_url
archived
assignees_url
blobs_url
branches_url
clone_url
collaborators_url
comments_url
commits_url
compare_url
contents_url
contributors_url
created_at
default_branch
deployments_url
description
downloads_url
events_url
fork
forks
forks_count
forks_url
full_name
git_commits_url
git_refs_url
git_tags_url
git_url
has_downloads
has_issues
has_pages
has_projects
has_wiki
homepage
hooks_url
html_url
id
issue_comment_url
issue_events_url
issues_url
keys_url
labels_url
language
languages_url
license
merges_url
milestones_url
mirror_url
name
node_id
notifications_url
open_issues
open_issues_count
owner
private
pulls_url
pushed_at
releases_url
score
size
ssh_url
stargazers_count
stargazers_url
statuses_url
subscribers_url
subscription_url
svn_url
tags_url
teams_url
trees_url
updated_at
url
watchers
watchers_count
#研究第一个仓库
repo_dict=repo_dicts[0]

print("\nSelected information about first repository:")
print('Name:',repo_dict['name'])
print('Owner:',repo_dict['owner']['login'])
print('Starts:',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'])

输出:

Selected information about first repository:
Name: awesome-python
Owner: vinta
Starts: 55562
Repository: https://github.com/vinta/awesome-python
Created: 2014-06-27T21:00:06Z
Updated: 2018-09-26T11:33:09Z
Description: A curated list of awesome Python frameworks, libraries, software and resources

1.6 概述最受欢迎的仓库

print("\nSelected information about each repository:")
for repo_dict in repo_dicts:
    print('\nName:',repo_dict['name'])
    print('Owner:',repo_dict['owner']['login']) 
    print('Starts:',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.7 监视API的速率限制
https://api.github.com/rate_limit
2、使用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("Starts code:",r.status_code)

#将API响应存储在一个变量中
response_dict=r.json()  #转化为python字典
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)   #创建简单条形图,让标签绕x轴旋转45度(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')

输出:

Starts code: 200
Total repositories: 3016003
image.png

2.1 改进Pygal图表
进行多方面的定制。

#可视化
my_style=LS('#333366',base_style=LCS)   #设置颜色等样式
my_config=pygal.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     #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) #创建简单条形图,让标签绕x轴旋转45度(x_label_rotation=45),并隐藏图例(show_legend=False)
chart=pygal.Bar(my_config,style=my_style)   #将my_config作为实参传递所有的配置设置
chart.title='Most-Starred Python Projects on GitHub'    #指定图表标题
chart.x_labels=names

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

输出:


image.png

2.2 添加自定义工具提示
在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','djangp','flask']

plot_dicts=[            #该列表包含三个字典,pygal根据键给条形创建工具
    {'value':16101,'label':'Description of httpie.'},
    {'value':15028,'label':'Description of django.'},
    {'valie':14798,'label':'Description of flask.'},
]

chart.add('',plot_dicts)
chart.render_to_file('bar_descriptions.svg')

输出:


image.png
上一篇下一篇

猜你喜欢

热点阅读