Flak 解析json数据不完整?

释放双眼,带上耳机,听听看~!

python flask框架解析post数据的坑

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

 1 $.ajax({
 2   \"url\":\"/test\",
 3   \"method\":\"post\",
 4   \"data\":{
 5       \"test\":[
 6         {\"test_dict\":\"1\"},
 7         {\"test_dict\":\"2\"},
 8         {\"test_dict\":\"3\"},
 9         ]
10       }
11   }
12 )

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

1 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参数了!

前端:

 1 $.ajax({
 2   \"url\":\"/test\",
 3   \"method\":\"post\",
 4   \"headers\":{\"Content-Type\": \"application/json;charset=utf-8\"},//这一句很重要!!!
 5   \"data\":{
 6     \"test\":[
 7         {\"test_dict\":\"1\"},
 8         {\"test_dict\":\"2\"},
 9         {\"test_dict\":\"3\"},
10       ]
11     }
12   }
  )

 

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

给TA打赏
共{{data.count}}人
人已打赏
随笔日记

初级Springboot(一)

2020-11-9 5:04:23

随笔日记

paper: The years of pedestrain Detection,what have we learned?

2020-11-9 5:04:25

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索