Flask處理前端POST過來的JSON
阿新 • • 發佈:2019-02-27
esp end ica final test 處理 ESS tail nic
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
Flask處理前端POST過來的JSON