Python實用模組(二十七)requests
阿新 • • 發佈:2021-01-18
軟硬體環境
windows 10 64bits
anaconda with python 3.7
requests 2.25.0
簡介
requests
是用來在Python
中進行標準HTTP
請求的第三方庫。它將請求背後的複雜性抽象成一個漂亮,簡單的API
,以便你可以專注於與服務互動和在應用程式中使用資料。
安裝
使用pip
進行安裝
pipinstallrequests
http請求格式
requests
的使用其實非常簡單,針對不同的http
方法,分別有不同的方法請求對應,如get
、post
、delete
等
importrequests #get請求 r=requests.get(url='url') r=requests.post(url='url') r=requests.put(url='url') r=requests.delete(url='url') r=requests.head(url='url') r=requests.options(url='url')
示例程式碼
利用前面我們分享的flask restful
教程,先寫個後臺程式
fromflaskimportFlask,jsonify,request fromflask_restfulimportApi,Resource,reqparse USERS=[ {"name":"zhangsan"}, {"name":"lisi"}, {"name":"wangwu"}, {"name":"zhaoliu"} ] classUsers(Resource): defget(self): returnjsonify(USERS) defpost(self): args=reqparse.RequestParser()\ .add_argument('name',type=str,location='json',required=True,help="名字不能為空")\ .parse_args() ifargs['name']notinUSERS: USERS.append({"name":args['name']}) returnjsonify(USERS) defdelete(self): USERS=[] returnjsonify(USERS) classUserId(Resource): def__init__(self): self.parser=reqparse.RequestParser() self.parser.add_argument('name',type=str) self.parser.add_argument('age',type=int) defget(self,userid): datas=self.parser.parse_args() returnjsonify( {"name":USERS[int(userid)].get('name'),"age":datas.get('age')} ) defpost(self,userid): file=request.files['file'] file.save('flask_file.txt') returnjsonify({ 'msg':'success' }) app=Flask(__name__) api=Api(app,default_mediatype="application/json") api.add_resource(Users,'/users') api.add_resource(UserId,'/user/<userid>') app.run(host='0.0.0.0',port=5000,use_reloader=True,debug=True)
完成後,啟動flask
服務
get請求示例
先看個不帶引數的get
請求
importrequests
r=requests.get('http://127.0.0.1:5000/users')
print(r.json())
print(r.status_code)
執行結果如下
再看個帶引數的get
請求
importrequests param={"name":"lisi","age":"18"} r=requests.get('http://127.0.0.1:5000/user/1',params=param) print(r.json()) print(r.status_code)
執行結果如下
post請求示例
再來看看post
請求,攜帶json
資料
importrequests
importjson
param={"name":"xgx"}
headers={"Content-type":"application/json"}
r=requests.post('http://127.0.0.1:5000/users',data=json.dumps(param),headers=headers)
print(r.json())
print(r.status_code)
執行結果如下
再來看看post
請求時提交檔案的示例
importrequests
files={'file':open('test.txt','rb')}
r=requests.post('http://127.0.0.1:5000/user/1',files=files)
print(r.json())
print(r.status_code)
執行結果如下
delete請求示例
最後看看delete
請求示例
importrequests
r=requests.delete('http://127.0.0.1:5000/users')
print(r.json())
print(r.status_code)
執行結果如下
Python實用模組專題
更多有用的python
模組,請移步
https://xugaoxiang.com/category/python/modules/
參考資料
https://requests.readthedocs.io/en/master/
Flask教程