您当前的位置:首页 > python

Python调用API接口的几种方式

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

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

- urllib2lcflinux系统宝典

- httplib2lcflinux系统宝典

- pycurllcflinux系统宝典

- requestslcflinux系统宝典

1.urllib2lcflinux系统宝典

- Sample1lcflinux系统宝典

import urllib2, urlliblcflinux系统宝典

github_url = 'https://api.github.com/user/repos'lcflinux系统宝典

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()lcflinux系统宝典

password_manager.add_password(None, github_url, 'user', '***')lcflinux系统宝典

auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handlerlcflinux系统宝典

opener = urllib2.build_opener(auth) # create an opener with the authentication handlerlcflinux系统宝典

urllib2.install_opener(opener) # install the opener...lcflinux系统宝典

request = urllib2.Request(github_url, urllib.urlencode({'name':'Test repo', 'description': 'Some test repository'})) # Manual encoding requiredlcflinux系统宝典

handler = urllib2.urlopen(request)lcflinux系统宝典

print handler.read()lcflinux系统宝典

  - Sample2lcflinux系统宝典

import urllib2lcflinux系统宝典

url = 'http://ems.vip.ebay.com/removeSIforcloud.cgi?ip=' + iplcflinux系统宝典

req = urllib2.Request(url)lcflinux系统宝典

req.add_header('IAF',abc.token_authiaas)lcflinux系统宝典

try:lcflinux系统宝典

    resp = urllib2.urlopen(req)lcflinux系统宝典

except urllib2.HTTPError, error:lcflinux系统宝典

    print "Cannot remove service instance!", errorlcflinux系统宝典

    sys.exit(1)lcflinux系统宝典

response = resp.read()lcflinux系统宝典

print responselcflinux系统宝典

lcflinux系统宝典
  - Sample3lcflinux系统宝典

import urllib2, urllib, base64lcflinux系统宝典

url = "https://reparo.stratus.ebay.com/reparo/bootstrap/registerasset/" + rackid + "/" + assetlcflinux系统宝典

data = urllib.urlencode({lcflinux系统宝典

                'reservedResource':'RR-',lcflinux系统宝典

                'resourceCapability':'Production',lcflinux系统宝典

                'movetoironic':'False',lcflinux系统宝典

                'output':'json'lcflinux系统宝典

        })lcflinux系统宝典

print "Bootstrap Asset jobs starting .............."lcflinux系统宝典

base64string = base64.encodestring('%s:%s' % (user, passwd)).replace('/n', '')lcflinux系统宝典

request = urllib2.Request(url, data, headers={"Authorization" : "Basic %s" % base64string})lcflinux系统宝典

response = urllib2.urlopen(request).read()lcflinux系统宝典

response_json = json.loads(response)lcflinux系统宝典

response_status = response_json['status']lcflinux系统宝典

status_code = response_status['statusCode']lcflinux系统宝典

status = response_status['status']lcflinux系统宝典

message = response_status['message']          lcflinux系统宝典

print status_code , status, messagelcflinux系统宝典

2. httplib2lcflinux系统宝典

import urllib, httplib2lcflinux系统宝典

github_url = 'lcflinux系统宝典

h = httplib2.Http(".cache")lcflinux系统宝典

h.add_credentials("user", "******", "lcflinux系统宝典

data = urllib.urlencode({"name":"test"})lcflinux系统宝典

resp, content = h.request(github_url, "POST", data)lcflinux系统宝典

print contentlcflinux系统宝典

3. pycurllcflinux系统宝典

import pycurl, jsonlcflinux系统宝典

github_url = "lcflinux系统宝典

user_pwd = "user:*****"lcflinux系统宝典

data = json.dumps({"name": "test_repo", "description": "Some test repo"})lcflinux系统宝典

c = pycurl.Curl()lcflinux系统宝典

c.setopt(pycurl.URL, github_url)lcflinux系统宝典

c.setopt(pycurl.USERPWD, user_pwd)lcflinux系统宝典

c.setopt(pycurl.POST, 1)lcflinux系统宝典

c.setopt(pycurl.POSTFIELDS, data)lcflinux系统宝典

c.perform()lcflinux系统宝典

4. requestslcflinux系统宝典

import requests, jsonlcflinux系统宝典

github_url = "lcflinux系统宝典

data = json.dumps({'name':'test', 'description':'some test repo'})lcflinux系统宝典

r = requests.post(github_url, data, auth=('user', '*****'))lcflinux系统宝典

print r.jsonlcflinux系统宝典

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

下面关于Python的文章您也可能喜欢,不妨看看:lcflinux系统宝典

Python:在指定目录下查找满足条件的文件  lcflinux系统宝典

Python2.7.7源码分析  lcflinux系统宝典

无需操作系统直接运行 Python 代码  lcflinux系统宝典

上源码安装Python3.4  lcflinux系统宝典

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] lcflinux系统宝典

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] lcflinux系统宝典

Python脚本获取Linux系统信息 lcflinux系统宝典

在下用Python搭建桌面算法交易研究环境 lcflinux系统宝典

Python 语言的发展简史 lcflinux系统宝典

Python 的详细介绍lcflinux系统宝典
Python 的下载地址lcflinux系统宝典



沪ICP备10206494号-4