學習Flask差不多兩個月了,說起來主要是為了幫忙做一個外包。整個過程就是不斷調整需求,看書,查文檔,實踐的循環。參考書主要是安道翻譯《Flask Web開發:基于Python的Web應用開發實戰》。現在也是個入門級水平,對于flask request 獲取參數進行一個總結。
知識點:
request請求總體分為兩類:
python的restful接收json。1.get請求
訪問時會在地址欄直接顯示參數不安全,且參數大小比較小。
2.post請求
參數不顯示在地址欄,一般用戶注冊、登錄都通過post請求完成。
flask前后端數據交互?flask獲取參數方式:
request.form.get("key", type=str, default=None) 獲取表單數據
request.args.get("key") 獲取get請求參數
request.values.get("key") 獲取所有參數
flask獲取post參數,本文主要介紹以上三種方式,其次也有獲取解析json數據格式,request.get_json(),這里不進行詳細介紹了。
下面直接開始試驗,以用戶注冊為例:
需要獲取四個參數:用戶手機號、密碼、校驗密碼、手機驗證碼
mobile = request.form.get("mobile")
flask框架實例、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)
整體代碼截圖
flask一直請求、分別通過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().
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态