相信做过自动化运维的同学都用过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 
29   - Sample3
30 
31 import urllib2, urllib, base64
32 url = "https://reparo.stratus.ebay.com/reparo/bootstrap/registerasset/" + rackid + "/" + asset
33 data = urllib.urlencode({
34                 'reservedResource':'RR-Hadoop',
35                 'resourceCapability':'Production',
36                 'movetoironic':'False',
37                 'output':'json'
38         })
39 
40 print "Bootstrap Asset jobs starting .............."
41 base64string = base64.encodestring('%s:%s' % (user, passwd)).replace('\n', '')
42 request = urllib2.Request(url, data, headers={"Authorization" : "Basic %s" % base64string})
43 response = urllib2.urlopen(request).read()
44 response_json = json.loads(response)
45 response_status = response_json['status']
46 status_code = response_status['statusCode']
47 status = response_status['status']
48 message = response_status['message']         
49 print status_code , status, message
View Code

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
View Code

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()
View Code

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
View Code

 

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

posted on 2015-12-03 14:38  muzinan110  阅读(430)  评论(0编辑  收藏  举报