request.values.get flask獲取表單所有數據三種方式之最強王者

知識點:

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

postman get 發送請求配置1

pycharm debuger 窗口變量截圖1

      在get請求下,request.form無法獲取參數,其他兩者都可以。

試驗2:通過postman將get請求改爲post請求

postman post發送請求配置2

pycharm debuger 窗口變量截圖2

        在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--

postman post發送請求配置3

pycharm debuger 窗口變量截圖3

        三者全部獲得參數值,最讓人困惑的是postForm獲得了mobile等值。此外需要注意的是postValues中含有全部的參數。

試驗4:post請求,刪除get部分參數

postman post發送請求配置4

pycharm debuger 窗口變量截圖4

       這次的結果倒是符合預期,postForm獲得form表單數據,postValues也能獲取到。

試驗5:補充實驗

postman post發送請求配置5

pycharm debuger 窗口變量截圖5

綜上,可以得出結論,request.form.get("key", type=str, default=None) 獲取表單數據,request.args.get("key") 獲取get請求參數,request.values.get("key") 獲取所有參數。推薦使用request.values.get().


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章