python调用API
相信做过自动化运维的同学都用过API接口来完成某些动作。API是一套成熟系统所必需的接口,可以被其他系统或脚本来调用,这也是自动化运维的必修课。
本文主要介绍Python中调用API的几种方式,下面是Python中会用到的库。
- urllib2
- httplib2
- pycurl
- requests
1.urllib2
- - Sample1
- import urllib2, urllib
- github_url = 'https://api.github.com/user/repos'
- password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
- password_manager.add_password(None, github_url, 'user', '***')
- auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handler
- opener = urllib2.build_opener(auth) # create an opener with the authentication handler
- urllib2.install_opener(opener) # install the opener...
- request = urllib2.Request(github_url, urllib.urlencode({'name':'Test repo', 'description': 'Some test repository'})) # Manual encoding required
- handler = urllib2.urlopen(request)
- print handler.read()
- - Sample2
- import urllib2
- url = 'http://ems.vip.ebay.com/removeSIforcloud.cgi?ip=' + ip
- req = urllib2.Request(url)
- req.add_header('IAF',abc.token_authiaas)
- try:
- resp = urllib2.urlopen(req)
- except urllib2.HTTPError, error:
- print "Cannot remove service instance!", error
- sys.exit(1)
- response = resp.read()
- print response
- - Sample3
- import urllib2, urllib, base64
- url = "https://reparo.stratus.ebay.com/reparo/bootstrap/registerasset/" + rackid + "/" + asset
- data = urllib.urlencode({
- 'reservedResource':'RR-Hadoop',
- 'resourceCapability':'Production',
- 'movetoironic':'False',
- 'output':'json'
- })
- print "Bootstrap Asset jobs starting .............."
- base64string = base64.encodestring('%s:%s' % (user, passwd)).replace('\n', '')
- request = urllib2.Request(url, data, headers={"Authorization" : "Basic %s" % base64string})
- response = urllib2.urlopen(request).read()
- response_json = json.loads(response)
- response_status = response_json['status']
- status_code = response_status['statusCode']
- status = response_status['status']
- message = response_status['message']
- print status_code , status, message
2. httplib2
- import urllib, httplib2
- github_url = '
- h = httplib2.Http(".cache")
- h.add_credentials("user", "******", "
- data = urllib.urlencode({"name":"test"})
- resp, content = h.request(github_url, "POST", data)
- print content
3. pycurl
- import pycurl, json
- github_url = "
- user_pwd = "user:*****"
- data = json.dumps({"name": "test_repo", "description": "Some test repo"})
- c = pycurl.Curl()
- c.setopt(pycurl.URL, github_url)
- c.setopt(pycurl.USERPWD, user_pwd)
- c.setopt(pycurl.POST, 1)
- c.setopt(pycurl.POSTFIELDS, data)
- c.perform()
4. requests
- import requests, json
- github_url = "
- data = json.dumps({'name':'test', 'description':'some test repo'})
- r = requests.post(github_url, data, auth=('user', '*****'))
- print r.json
以上几种方式都可以调用API来执行动作,但requests这种方式代码最简洁,最清晰,建议采用。
python调用API的更多相关文章
- Python调用API接口的几种方式 数据库 脚本
Python调用API接口的几种方式 2018-01-08 gaoeb97nd... 转自 one_day_day... 修改 微信分享: 相信做过自动化运维的同学都用过API接口来完成某些动作.AP ...
- Python调用API接口的几种方式
Python调用API接口的几种方式 相信做过自动化运维的同学都用过API接口来完成某些动作.API是一套成熟系统所必需的接口,可以被其他系统或脚本来调用,这也是自动化运维的必修课. 本文主要介绍py ...
- python调用api方式
1.shell版本 #!/bin/bash #根据api提供商,获取指定时间格式 datestr=`xxx` #根据api提供商,获取指定加盐密码格式 pwdstr=`xxx` curl -s -X ...
- python 调用API时异常捕获的技巧
- 『Python』Python 调用 ZoomEye API 批量获取目标网站IP
#### 20160712 更新 原API的访问方式是以 HTTP 的方式访问的,根据官网最新文档,现在已经修改成 HTTPS 方式,测试可以正常使用API了. 0x 00 前言 ZoomEye 的 ...
- 如何用 Python 和 API 收集与分析网络数据?
摘自 https://www.jianshu.com/p/d52020f0c247 本文以一款阿里云市场历史天气查询产品为例,为你逐步介绍如何用 Python 调用 API 收集.分析与可视化数据.希 ...
- 使用Python调用Flickr API抓取图片数据
Flickr是雅虎旗下的图片分享网站,上面有全世界网友分享的大量精彩图片,被认为是专业的图片网站.其API也很友好,可以实现多种功能.这里我使用了Python调用其API获得了大量的照片数据.需要注意 ...
- paip.java c# .net php python调用c++ c dll so windows api 总结
paip.java c# .net php python调用c++ c dll so windows api 总结 作者Attilax 艾龙, EMAIL:1466519819@qq.com 来 ...
- python调用openstack的api,create_instance的程序解析
python调用openstack的api,create_instance的程序解析 2017年10月17日 15:27:24 CloudXli 阅读数:848 版权声明:本文为博主原创文章,未经 ...
随机推荐
- CCF - 最大矩形
试题编号: 201312-3 试题名称: 最大的矩形 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 在横轴上放了n个相邻的矩形,每个矩形的宽度是1,而第i(1 ≤ i ≤ n ...
- LaTeX公式
在学习机器学习中会接触到大量的数学公式,所以在写博客是会非常的麻烦.用公式编辑器一个一个写会非常的麻烦,这时候我们可以使用LaTeX来插入公式. 写这篇博文的目的在于,大家如果要编辑一些简单的公式,就 ...
- Java精选笔记_Servlet技术
Servlet技术 Servlet开发入门 Servlet接口 针对Servlet技术的开发,SUN公司提供了一系列接口和类,其中最重要的是javax.servlet.Servlet接口. Servl ...
- IDEA Intellij 打开springboot项目 配置文件无法出现输入提示
需要将java代码和资源文件进行标记
- 关于“ORA-01747: user.table.column, table.column 或列说明无效”的报错。
今天在工程中遇到“ORA-01747: user.table.column, table.column 或列说明无效”的报错情况,查了一下是由于数据库列名起的不好引起的,名字用到了数据库的关键字.
- 【go】用Golang的 http 包建立 Web 服务器
web.go package main import ( "fmt" "log" "net/http" "strings" ...
- MUI 分享功能(微信、QQ 、朋友圈)
配置文件:manifest.json plus ->plugins 下边 "share": {/*配置应用使用分享功能,参考http://ask.dcloud.net.cn/ ...
- [转]C++结构体|类 内存对齐详解
内存地址对齐,是一种在计算机内存中排列数据(表现为变量的地址).访问数据(表现为CPU读取数据)的一种方式,包含了两种相互独立又相互关联的部分:基本数据对齐和结构体数据对齐 . 为什么需要内存对齐?对 ...
- LeetCode——Intersection of Two Linked Lists
Description: Write a program to find the node at which the intersection of two singly linked lists b ...
- 用Iterator实现遍历集合
使用Collection类的Iterator,可以方便的遍历Vector, ArrayList, LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码. 示例: C ...