python使用api接口,Python接口调用
大蟒调用美国石油学会(美国石油协会)的几种方式:
1、urllib2
defrun(self):
用户名,密码=getword()
尝试:
打印-*12
打印"用户:",用户名,"密码:",密码
req=urllib2 .请求(sys.argv[1])
passman=urllib2 .HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None,sys.argv[1],用户名,密码)
authhandler=urllib2 .HTTPBasicAuthHandler(passman)
opener=URL lib 2。build _ opener(身份验证处理程序)
fd=opener.open(req)
打印 \ t \ n \用户名: ,用户名,密码: ,密码-登录成功!\n\n
printRetrieved ,fd.geturl()
info=fd.info()
forkey,valueininfo.items():
打印% s=% s“%(键,值)
系统退出(2)
除了(urllib2 .HTTPError,httplib .BadStatusLine,socket.error),msg:
打印" Anerroroccurred: ",消息
及格相关推荐: 《Python教程》
2、urllib
defdorequest(url,dat
a="",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.justimplementwhatwewant3、pycurl
defput(url,data,headers={}):4、requests"""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
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,...}
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。