python中调用API的几种方式:
– urllib2
– requests
一、调用别人的接口
案例1、urllib2
importurllib2, urllib
github_url=’https://api.github.com/user/repos’password_manager=urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None,github_url,’user’, ‘***’)
auth=urllib2.HTTPBasicAuthHandler(password_manager)#create an authentication handler
opener = urllib2.build_opener(auth)#create an opener with the authentication handler
urllib2.install_opener(opener)#install the opener
…
request=urllib2.Request(github_url,
urllib.urlencode({‘name’: ‘Test repo’,’description’: ‘Some test repository’}))#Manual encoding required
handler =urllib2.urlopen(request)print handler.read()
案例2、requests
importrequests, json
github_url= “data = json.dumps({‘name’:’test’, ‘description’:’some test repo’})
r= requests.post(github_url, data, auth=(‘user’, ‘*****’))print r.json
importrequestsfrom lxml importetreefrom random importrandintdefget_joke():
url=”http://www.qiushibaike.com/text/page/”+ str(randint(1,5))
r=requests.get(url)
tree=etree.HTML(r.text)
contentlist= tree.xpath(‘//div[@class=”content”]/span’)
jokes=[]for content incontentlist:
content= content.xpath(‘string(.)’) #string() 函数将所有子文本串联起来,# 必须传递单个节点,而不是节点集。
if ‘查看全文’ in content: #忽略包含“查看原文”笑话
continuejokes.append(content)
joke= jokes[randint(1, len(jokes))].strip()returnjokeif __name__ == “__main__”:
content=get_joke()print(content)
二、python一个http接口服务,给别人调用 —-之Flask
案例1、flask、get接口代码实现
#-*- coding: UTF-8 -*-
#flask
from flask importFlask, request, jsonify
app= Flask(__name__)
@app.route(‘/test’, methods=[“GET”])defcalculate():
a= request.args.get(“a”, 0)
b= request.args.get(“b”, 0)
c= int(a) +int(b)
res= {“result”: c}return jsonify(content_type=’application/json;charset=utf-8′,
reason=’success’,
charset=’utf-8′,
status=’200′,
content=res)if __name__ == ‘__main__’:
app.run(host=’0.0.0.0′,
threaded=True,
debug=False,
调用方式:
案例2、post接口flask
from flask importFlask, request, jsonify
app= Flask(__name__)
@app.route(‘/test’, methods=[“POST”])defcalculate():
params= request.form if request.form elserequest.jsonprint(params)
a= params.get(“a”, 0)
b= params.get(“b”, 0)
c= a +b
res= {“result”: c}return jsonify(content_type=’application/json;charset=utf-8′,
reason=’success’,
charset=’utf-8′,
status=’200′,
content=res)if __name__ == ‘__main__’:
app.run(host=’0.0.0.0′,
threaded=True,
debug=True,
port=8080)
调用方式
http://127.0.0.1:8080/test
最常用接口形式
POST API接口:importjsonimportrequestsif __name__ == ‘__main__’:
url= “http://127.0.0.1:9001/rsa/set_uplod”headers= {‘content-type’: ‘application/json’}
requestData= {“certificate_no”: “56565656565656”, “auth_code”: “123456”}
ret= requests.post(url, json=requestData, headers=headers)if ret.status_code == 200:
text=json.loads(ret.text)print(text)
get API 接口:importjsonimportrequestsif __name__ == ‘__main__’:
url= “http://127.0.0.1:9001/getSha1Test?message=APP000051527151133935949D49FDC0A86605313931B9BB9A4C87″ret=requests.get(url)if ret.status_code == 200:
text=json.loads(ret.text)print(text)
三、二、python一个http接口服务,给别人调用 —-之FastAPI
这次选择fastapi,FastAPI是一个现代的、快速(高性能)的web框架,用于基于标准Python类型提示使用Python 3.6+构建api。具有快速、快速编码、更少的错误、直观、简单、简便、健壮。简易而且本地win10能够跑起来。
二、FastAPI的get接口代码实现
1. 安装: pip install fastapi
pip install uvicorn
#!/usr/bin/python
from fastapi importFastAPI
app=FastAPI()
@app.get(‘/test/a={a}/b={b}’)def calculate(a: int=None, b: int=None):
c= a +b
res= {“res”:c}returnresif __name__ == ‘__main__’:importuvicorn
uvicorn.run(app=app,
host=”0.0.0.0″,
port=8080,
workers=1)
from pydantic importBaseModelfrom fastapi importFastAPI
app=FastAPI()classItem(BaseModel):
a: int=None
b: int=None
@app.post(‘/test’)defcalculate(request_data: Item):
a=request_data.a
b=request_data.b
c= a +b
res= {“res”:c}returnresif __name__ == ‘__main__’:importuvicorn
uvicorn.run(app=app,
host=”0.0.0.0″,
port=8080,
workers=1)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/36710.html