python flask 框架解析 post 数据的坑
当使用 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 获取前端的数据时, 发现获取到的数据是这样的:
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 参数了!
前端:
- $.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 数据啦!
来源: https://www.cnblogs.com/zhongbr/p/python_flask.html