python调用api的几种方式:
1、urllib2
defrun(self): username,password=getword() try: print"-"*12 print"User:",username,"Password:",password req=urllib2.Request(sys.argv[1]) passman=urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None,sys.argv[1],username,password) authhandler=urllib2.HTTPBasicAuthHandler(passman) opener=urllib2.build_opener(authhandler) fd=opener.open(req) print"\t\n\nUsername:",username,"Password:",password,"-----Loginsuccessful!!!\n\n" print"Retrieved",fd.geturl() info=fd.info() forkey,valueininfo.items(): print"%s=%s"%(key,value) sys.exit(2) except(urllib2.HTTPError,httplib.BadStatusLine,socket.error),msg: print"Anerroroccurred:",msg pass
相关推荐:《Python教程》
2、urllib
defdorequest(url,data="",method='GET'):
try:
ifmethod=='GET':
response=urllib.request.urlopen(url,timeout=10).read()
else:
#usePUT/DELETE/POST,datashouldbeencodedinascii/bytes
request=urllib.request.Request(url,data=data.encode('ascii'),method=method)
response=urllib.request.urlopen(request,timeout=10).read()
#etcdmayreturnjsonresultwithresponsehttperrorcode
#httperrorcodewillraiseexceptioninurlopen
#catchtheHTTPErrorandgetthejsonresult
excepturllib.error.HTTPErrorase:
#e.fpmustberead()inthisexceptblock.
#theewillbedeletedande.fpwillbeclosedafterthisblock
response=e.fp.read()
#responseisencodedinbytes.
#recodedinutf-8andloadedinjson
result=json.loads(str(response,encoding='utf-8'))
returnresult
#clienttouseetcd
#notallAPIsareimplementedbelow.justimplementwhatwewant
3、pycurl
defput(url,data,headers={}):
"""MakeaPUTrequesttotheurl,usingdatainthemessagebody,
withtheadditionalheaders,ifany"""
reply=-1#default,non-httpresponse
curl=pycurl.Curl()
curl.setopt(pycurl.URL,url)
iflen(headers)>0:
curl.setopt(pycurl.HTTPHEADER,[k+':'+vfork,vinheaders.items()])
curl.setopt(pycurl.PUT,1)
curl.setopt(pycurl.INFILESIZE,len(data))
databuffer=StringIO(data)
curl.setopt(pycurl.READFUNCTION,databuffer.read)
try:
curl.perform()
reply=curl.getinfo(pycurl.HTTP_CODE)
exceptException:
pass
curl.close()
returnreply
4、requests
importrequests
>>>r=requests.get('https://api.github.com/user',auth=('user','pass'))
>>>r.status_code
200
>>>r.headers['content-type']
'application/json;charset=utf8'
>>>r.encoding
'utf-8'
>>>r.text
u'{"type":"User"...'
>>>r.json()
{u'private_gists':419,u'total_private_repos':77,...}
上一篇