标签:csdn blank headers end 数据 fun char nal route
POST JSON数据的JS代码:
$.ajax({ url:‘http://127.0.0.1:5000/calc‘, type : ‘post‘, dataType:‘json‘, headers: { "Content-Type": "application/json;charset=utf-8" }, contentType:‘application/json; charset=utf-8‘, data:JSON.stringify({D:D,q:q,ls:ls,Lz:Lz,l:l,Uz:Uz,u:u,y:y,P:P,h1:h1,data_list:data_lists}), success:function(data){ $("#finally").show(); } })
对于前端POST请求发送过来的json数据,Flask后台可使用 request.get_data() 来接收数据,数据的格式为 bytes;加上as_text=True 参数后就变成 Unicode 了; 再使用 json.loads() 方法就可以转换字典。
示例代码:
from flask import Flask, render_template, request, make_response import json import light_calc app = Flask(__name__) app.debug = True @app.route(‘/‘, methods=[‘POST‘, ‘GET‘]) def main(): return render_template(‘test_inputs.html‘) @app.route(‘/calc‘, methods=[‘POST‘]) def calc(): data_list = [] data = json.loads(request.get_data(as_text=True)) # request.get_data(as_text=True) : 获取前端POST请求传过来的 json 数据 for key, value in data.items(): if value == ‘‘: data[key] = 0 for key, value in data.items(): if type(value) == str and value != ‘i‘: data[key] = float(value) for i in data[‘data_list‘]: new_dict = {} new_dict[‘r‘] = float(i[‘r‘]) new_dict[‘d‘] = float(i[‘d‘]) new_dict[‘n‘] = float(i[‘n‘]) new_dict[‘n_2‘] = float(i[‘n_2‘]) data_list.append(new_dict) print(data) print(data_list) try: result = light_calc.main(data[‘D‘], data[‘q‘], data[‘ls‘], data[‘Lz‘], data[‘Uz‘], data[‘l‘], data[‘u‘], data[‘y‘], data[‘P‘], data[‘h1‘], data_list) resp = make_response(result) resp.headers[‘Content-Type‘] = ‘text/json‘ return result except Exception as e: print(e) return ‘{"status":"500"}‘ if __name__ == ‘__main__‘: app.run()
参考链接:https://blog.csdn.net/qq_29113041/article/details/80392597
标签:csdn blank headers end 数据 fun char nal route
原文地址:https://www.cnblogs.com/neozheng/p/10440405.html