python flask解析json数据不完整的解决方法

yipeiwu_com7年前Python基础

当使用Python的flask框架来开发网站后台,解析前端Post来的数据,通常都会使用request.form来获取前端传过来的数据,但是如果传过来的数据比较复杂,其中右array,而且array的元素不是单个的数字或者字符串的时候,就会出现解析不到数据的情况,比如使用下面的js代码向python flask传递数据

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

当我们使用flask的request.form获取前端的数据时,发现获取到的数据是这样的:

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

???我的Post数据呢?给我post到哪里去了???

这里我就去网上查解决办法,但是网上哪些删么使用reqeust.form.getlist()方法好像都对我无效,但是又找不到其他的解决方案?怎么办?

规范一下自己的请求,在前端请求的时候设置一个Json的请求头,在flask框架钟直接使用json.loads()方法解析reqeust.get_data(as_text=True),就可以解析到完整的post参数了!

前端:

$.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数据啦!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pytorch实现特殊的Module--Sqeuential三种写法

我就废话不多说了,直接上代码吧! # -*- coding: utf-8 -*- #@Time :2019/7/1 13:34 #@Author :XiaoMa import...

Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法

Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法

本文实例讲述了Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法。分享给大家供大家参考,具体如下: 问题 输入 第1行:字符串A 第2行:字符串B (A,B的长度 <...

详解python调度框架APScheduler使用

最近在研究python调度框架APScheduler使用的路上,那么今天也算个学习笔记吧! # coding=utf-8 """ Demonstrates how to use t...

python通过http下载文件的方法详解

1、通过requests.get方法 r = requests.get("http://200.20.3.20:8080/job/Compile/job/aaa/496/artifa...

python 实现识别图片上的数字

python 实现识别图片上的数字

Python 3.6 版本 Pytesseract 图像验证码识别 环境: (1) win7 64位 (2) Idea (3) python 3.6 (4) pip install pi...