request請求總體分為兩類:
1.get請求
訪問時會在地址欄直接顯示參數不安全,且參數大小比較小。
2.post請求
參數不顯示在地址欄,一般用戶注冊、登錄都通過post請求完成。
flask獲取參數方式:
request.form.get("key", type=str, default=None) 獲取表單數據
request.args.get("key") 獲取get請求參數
request.values.get("key") 獲取所有參數
本文主要介紹以上三種方式,其次也有獲取解析json數據格式,request.get_json(),這里不進行詳細介紹了。
下面直接開始試驗,以用戶注冊為例:
需要獲取四個參數:用戶手機號、密碼、校驗密碼、手機驗證碼
mobile = request.form.get("mobile")
password = request.form.get("password",type=str,default=None)
password_repeat = request.form.get("password_repeat",type=str,default=None)
mobile_code = request.form.get("mobile_code",type=str,default=None)

分別通過3中方式獲取參數:request.form, request.args,request.values
postForm= request.form
getArgs= request.args
postValues= request.values
試驗:
試驗1::Get請求:將參數直接拼接在url上,以下均以postman, pycharm調試窗截圖說明。
url:http://127.0.0.1:5000/register?mobile=18817366807&password=123456&password_repeat=123456&mobile_code=111111


在get請求下,request.form無法獲取參數,其他兩者都可以。
試驗2:通過postman將get請求改為post請求


在post請求下,request.form無法獲取有效參數,其他兩者都可以,當然content-type/form-data 發生改變,當然這里可也簡單理解為該請求為偽post請求。
試驗3:post請求,在body內創建form-data參數成員
POST /register?mobile=18817366807&password=123456&password_repeat=123456&mobile_code=111111 HTTP/1.1
Host: 127.0.0.1:5000
Cache-Control: no-cache
Postman-Token: 31fff394-653b-ac72-6011-313518d4c2eb
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="formmember"
form
------WebKitFormBoundary7MA4YWxkTrZu0gW--


三者全部獲得參數值,最讓人困惑的是postForm獲得了mobile等值。此外需要注意的是postValues中含有全部的參數。
試驗4:post請求,刪除get部分參數


這次的結果倒是符合預期,postForm獲得form表單數據,postValues也能獲取到。
試驗5:補充實驗


綜上,可以得出結論,request.form.get("key", type=str, default=None) 獲取表單數據,request.args.get("key") 獲取get請求參數,request.values.get("key") 獲取所有參數。推薦使用request.values.get().
作者:碼農的happy_life
鏈接:https://www.jianshu.com/p/ecd97b1c21c1
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。