相信做过自动化运维的同学都用过API接口来完成某些动作。API是一套成熟系统所必需的接口,可以被其他系统或脚本来调用,这也是自动化运维的必修课。

本文主要介绍Python中调用API的几种方式,下面是Python中会用到的库。

- urllib2

- httplib2

- pycurl

- requests

1.urllib2

  1. - Sample1
  2.  
  3. import urllib2, urllib
  4. github_url = 'https://api.github.com/user/repos'
  5. password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
  6. password_manager.add_password(None, github_url, 'user', '***')
  7. auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handler
  8. opener = urllib2.build_opener(auth) # create an opener with the authentication handler
  9. urllib2.install_opener(opener) # install the opener...
  10. request = urllib2.Request(github_url, urllib.urlencode({'name':'Test repo', 'description': 'Some test repository'})) # Manual encoding required
  11. handler = urllib2.urlopen(request)
  12. print handler.read()
  13.  
  14. - Sample2
  15.  
  16. import urllib2
  17. url = 'http://ems.vip.ebay.com/removeSIforcloud.cgi?ip=' + ip
  18. req = urllib2.Request(url)
  19. req.add_header('IAF',abc.token_authiaas)
  20. try:
  21. resp = urllib2.urlopen(req)
  22. except urllib2.HTTPError, error:
  23. print "Cannot remove service instance!", error
  24. sys.exit(1)
  25. response = resp.read()
  26. print response
  27.  
  28. - Sample3
  29.  
  30. import urllib2, urllib, base64
  31. url = "https://reparo.stratus.ebay.com/reparo/bootstrap/registerasset/" + rackid + "/" + asset
  32. data = urllib.urlencode({
  33. 'reservedResource':'RR-Hadoop',
  34. 'resourceCapability':'Production',
  35. 'movetoironic':'False',
  36. 'output':'json'
  37. })
  38.  
  39. print "Bootstrap Asset jobs starting .............."
  40. base64string = base64.encodestring('%s:%s' % (user, passwd)).replace('\n', '')
  41. request = urllib2.Request(url, data, headers={"Authorization" : "Basic %s" % base64string})
  42. response = urllib2.urlopen(request).read()
  43. response_json = json.loads(response)
  44. response_status = response_json['status']
  45. status_code = response_status['statusCode']
  46. status = response_status['status']
  47. message = response_status['message']
  48. print status_code , status, message

2. httplib2

  1. import urllib, httplib2
  2. github_url = '
  3. h = httplib2.Http(".cache")
  4. h.add_credentials("user", "******", "
  5. data = urllib.urlencode({"name":"test"})
  6. resp, content = h.request(github_url, "POST", data)
  7. print content

3. pycurl

  1. import pycurl, json
  2. github_url = "
  3. user_pwd = "user:*****"
  4. data = json.dumps({"name": "test_repo", "description": "Some test repo"})
  5. c = pycurl.Curl()
  6. c.setopt(pycurl.URL, github_url)
  7. c.setopt(pycurl.USERPWD, user_pwd)
  8. c.setopt(pycurl.POST, 1)
  9. c.setopt(pycurl.POSTFIELDS, data)
  10. c.perform()

4. requests

  1. import requests, json
  2. github_url = "
  3. data = json.dumps({'name':'test', 'description':'some test repo'})
  4. r = requests.post(github_url, data, auth=('user', '*****'))
  5. print r.json

以上几种方式都可以调用API来执行动作,但requests这种方式代码最简洁,最清晰,建议采用。

python调用API的更多相关文章

  1. Python调用API接口的几种方式 数据库 脚本

    Python调用API接口的几种方式 2018-01-08 gaoeb97nd... 转自 one_day_day... 修改 微信分享: 相信做过自动化运维的同学都用过API接口来完成某些动作.AP ...

  2. Python调用API接口的几种方式

    Python调用API接口的几种方式 相信做过自动化运维的同学都用过API接口来完成某些动作.API是一套成熟系统所必需的接口,可以被其他系统或脚本来调用,这也是自动化运维的必修课. 本文主要介绍py ...

  3. python调用api方式

    1.shell版本 #!/bin/bash #根据api提供商,获取指定时间格式 datestr=`xxx` #根据api提供商,获取指定加盐密码格式 pwdstr=`xxx` curl -s -X ...

  4. python 调用API时异常捕获的技巧

  5. 『Python』Python 调用 ZoomEye API 批量获取目标网站IP

    #### 20160712 更新 原API的访问方式是以 HTTP 的方式访问的,根据官网最新文档,现在已经修改成 HTTPS 方式,测试可以正常使用API了. 0x 00 前言 ZoomEye 的 ...

  6. 如何用 Python 和 API 收集与分析网络数据?

    摘自 https://www.jianshu.com/p/d52020f0c247 本文以一款阿里云市场历史天气查询产品为例,为你逐步介绍如何用 Python 调用 API 收集.分析与可视化数据.希 ...

  7. 使用Python调用Flickr API抓取图片数据

    Flickr是雅虎旗下的图片分享网站,上面有全世界网友分享的大量精彩图片,被认为是专业的图片网站.其API也很友好,可以实现多种功能.这里我使用了Python调用其API获得了大量的照片数据.需要注意 ...

  8. 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 来 ...

  9. python调用openstack的api,create_instance的程序解析

    python调用openstack的api,create_instance的程序解析 2017年10月17日 15:27:24 CloudXli 阅读数:848   版权声明:本文为博主原创文章,未经 ...

随机推荐

  1. CCF - 最大矩形

    试题编号: 201312-3 试题名称: 最大的矩形 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 在横轴上放了n个相邻的矩形,每个矩形的宽度是1,而第i(1 ≤ i ≤ n ...

  2. LaTeX公式

    在学习机器学习中会接触到大量的数学公式,所以在写博客是会非常的麻烦.用公式编辑器一个一个写会非常的麻烦,这时候我们可以使用LaTeX来插入公式. 写这篇博文的目的在于,大家如果要编辑一些简单的公式,就 ...

  3. Java精选笔记_Servlet技术

    Servlet技术 Servlet开发入门 Servlet接口 针对Servlet技术的开发,SUN公司提供了一系列接口和类,其中最重要的是javax.servlet.Servlet接口. Servl ...

  4. IDEA Intellij 打开springboot项目 配置文件无法出现输入提示

    需要将java代码和资源文件进行标记

  5. 关于“ORA-01747: user.table.column, table.column 或列说明无效”的报错。

    今天在工程中遇到“ORA-01747: user.table.column, table.column 或列说明无效”的报错情况,查了一下是由于数据库列名起的不好引起的,名字用到了数据库的关键字.

  6. 【go】用Golang的 http 包建立 Web 服务器

    web.go package main import ( "fmt" "log" "net/http" "strings" ...

  7. MUI 分享功能(微信、QQ 、朋友圈)

    配置文件:manifest.json plus ->plugins 下边 "share": {/*配置应用使用分享功能,参考http://ask.dcloud.net.cn/ ...

  8. [转]C++结构体|类 内存对齐详解

    内存地址对齐,是一种在计算机内存中排列数据(表现为变量的地址).访问数据(表现为CPU读取数据)的一种方式,包含了两种相互独立又相互关联的部分:基本数据对齐和结构体数据对齐 . 为什么需要内存对齐?对 ...

  9. LeetCode——Intersection of Two Linked Lists

    Description: Write a program to find the node at which the intersection of two singly linked lists b ...

  10. 用Iterator实现遍历集合

    使用Collection类的Iterator,可以方便的遍历Vector, ArrayList, LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码. 示例: C ...