【问题标题】:Python flask request returns undefined valuesPython烧瓶请求返回未定义的值
【发布时间】:2023-04-03 06:07:01
【问题描述】:

我想将数组传递给 Python Flask,但结果为空或 b'undefined=&undefined=&undefined='。这是我的代码 Javascript

var test = [1, 2, 3];
  $.ajax({
        url: '/table',
        data : test,
        type: 'POST',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

和 Python 代码

app.route('/table', methods = ['POST'])
def table():
    #print(request.values)
    print(request.get_data())
    return 'got this'

【问题讨论】:

    标签: python jquery ajax flask


    【解决方案1】:

    您需要使用JSON 发送回javascript 中的数组、对象等值:

    var test = [1, 2, 3];
    $.ajax({
        url: '/table',
        data : {'payload':JSON.stringify(test)},
        type: 'get',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });
    

    然后,在应用程序中:

    import json
    @app.route('/table')
    def table():
      _result = json.loads(flask.request.args.get('payload'))
      return 'got this'
    

    【讨论】:

    • 奇怪它返回TypeError:JSON对象必须是str,bytes或bytearray,而不是'NoneType'
    • @MrLukas 请立即尝试。我更改了请求类型,因为 data 似乎没有被正确传回
    • 现在它就像一个魅力。我花了 5 个小时试图将其作为 POST 传递。我想知道为什么它不起作用,但多亏了你,我现在可以继续前进。谢谢
    【解决方案2】:

    使用 JavaScript 对象并作为application/json 的内容发送。

    var test = {'input_1': 1, 'input_2': 2, 'input_3': 3};
      $.ajax({
            url: '/table',
            data : JSON.stringify(test),
            contentType: 'application/json',
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    

    在您的烧瓶应用程序中,您不需要 import json 来加载接收到的数据,因为您已将内容发送为 application/json。

    from flask import jsonify, request
    
    @app.route('/table', methods = ['POST'])
    def table():
      _result = request.json  # because you have sent data as content type as application/json
      return jsonify(_result)  # jsonify will response data as `application/json` header.
      #  {'input_1': 1, 'input_2': 2, 'input_3': 3}
    

    【讨论】:

    • 是的,但问题是我可以将它存储为 JSON (key, value) 我只想传递数组
    • 如果您发送内容类型为json,则无需使用json 加载,您的数据将在request.json 中作为密钥对可用。你的json.loads(__result) 是多余的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2018-07-28
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多