轉載自:https://zhuanlan.zhihu.com/p/158653107
前後端分離開發是目前web開發最流行的方式之一,本文以python web開發常用架構-flask為例,講解flask如何使用request來擷取前端傳輸的各種類型資料。
下面,文章針對不同的場景來展示requeset如何處理接收的資料。
二種方式發送請求:
linux: 以CURL來發送API請求
前端:http發送API請求
-
參數在url中
HTTP請求
POST /test?params=test HTTP/1.1
Host: 127.0.0.1:5000
cache-control: no-cache
CURL請求
curl -X POST
'http://127.0.0.1:5000/test?params=test'
-H 'cache-control: no-cache'
Python代碼
request.values.get('params')
request.args.get('params')
-
token在header中
HTTP請求
POST /test HTTP/1.1
Host: 127.0.0.1:5000
token: this is a token
cache-control: no-cache
CURL請求
curl -X POST
http://127.0.0.1:5000/test
-H 'cache-control: no-cache'
-H 'token: this is a token'
Python代碼
request.headers.get('token')
-
body下的form-data
HTTP請求
POST /test HTTP/1.1
Host: 127.0.0.1:5000
cache-control: no-cache
Content-Type: multipart/form-data;
Content-Disposition: form-data; name="key"
value
Content-Disposition: form-data; name="file"; filename="C:\Users\x1c\Desktop\3.jpg
CURL請求
curl -X POST
http://127.0.0.1:5000/test
-H 'cache-control: no-cache'
-H 'content-type: multipart/form-data;'
-F key=value
-F 'file=@C:\Users\x1c\Desktop\3.jpg'
Python代碼
request.form.get('key')
request.files
結果
value
ImmutableMultiDict([('file', <FileStorage: '3.jpg' ('image/jpeg')>)])
4. body下的json
CURL請求
curl -X POST
http://127.0.0.1:5000/test
-H 'Content-Type: application/json'
-H 'cache-control: no-cache'
-d '{"key":"this is a json"}'
HTTP請求
POST /test HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: application/json
cache-control: no-cache
{"key":"this is a json"}
Python代碼
request.json