• Flask处理前端POST过来的JSON数据


    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

  • 相关阅读:
    BOM-Window窗口对象
    BOM
    案例:电灯开关
    事件简单学习
    简单学习
    ECMAScript基本对象——Global全局对象
    ECMAScript基本对象——RegExp 正则表达式对象
    ECMAScript基本对象——String 对象
    zk安装管理
    kafka服务器批量copy文件脚本
  • 原文地址:https://www.cnblogs.com/neozheng/p/10440405.html
Copyright © 2020-2023  润新知