亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python flask解析json數(shù)據(jù)不完整的解決方法

 更新時間:2019年05月26日 10:38:06   作者:鐘擺人  
這篇文章主要介紹了python flask解析json數(shù)據(jù)不完整的解決方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

當(dāng)使用Python的flask框架來開發(fā)網(wǎng)站后臺,解析前端Post來的數(shù)據(jù),通常都會使用request.form來獲取前端傳過來的數(shù)據(jù),但是如果傳過來的數(shù)據(jù)比較復(fù)雜,其中右array,而且array的元素不是單個的數(shù)字或者字符串的時候,就會出現(xiàn)解析不到數(shù)據(jù)的情況,比如使用下面的js代碼向python flask傳遞數(shù)據(jù)

$.ajax({
  "url":"/test",
  "method":"post",
  "data":{
      "test":[
        {"test_dict":"1"},
        {"test_dict":"2"},
        {"test_dict":"3"},
        ]
      }
  }
)

當(dāng)我們使用flask的request.form獲取前端的數(shù)據(jù)時,發(fā)現(xiàn)獲取到的數(shù)據(jù)是這樣的:

ImmutableMultiDict([('test', 'test_dict'), ('test', 'test_dict'), ('test', 'test_dict')])

???我的Post數(shù)據(jù)呢?給我post到哪里去了???

這里我就去網(wǎng)上查解決辦法,但是網(wǎng)上哪些刪么使用reqeust.form.getlist()方法好像都對我無效,但是又找不到其他的解決方案?怎么辦?

規(guī)范一下自己的請求,在前端請求的時候設(shè)置一個Json的請求頭,在flask框架鐘直接使用json.loads()方法解析reqeust.get_data(as_text=True),就可以解析到完整的post參數(shù)了!

前端:

$.ajax({
  "url":"/test",
  "method":"post",
  "headers":{"Content-Type": "application/json;charset=utf-8"},//這一句很重要!?。?
  "data":{
    "test":[
        {"test_dict":"1"},
        {"test_dict":"2"},
        {"test_dict":"3"},
      ]
    }
  }
  )

python代碼:

@app.route("/test",methods=["GET","POST"])
def test():
  print(json.loads(request.get_data(as_text=True)))
  return ""

然后看看后臺打印的信息:

* Serving Flask app "test_flask.py"
* Environment: development
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
{'test': [{'test_dict': '1'}, {'test_dict': '2'}, {'test_dict': '3'}]}
127.0.0.1 - - [25/May/2019 22:43:08] "POST /test HTTP/1.1" 200 -

問題解決,可以解析到完整的json數(shù)據(jù)啦!

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論