简体   繁体   中英

how can I pass a dictionary from javascript to flask?

I want to pass a dictionary (button_state) from javascript to python using flask and jquery. On the jquery side, I have:

$(".btn#submit").click(function(event){
    newdata = JSON.stringify(buttons_state);
    console.log("submission button POST attempt: " + newdata)

    $.ajax({
        url: '/submission',
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: newdata,
        processData: false,
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
    });

});

On the server side:

@app.route('/submission', methods=['POST'])
def submission():
    info = request.get_json(silent=False)
    return info

But I am getting an Error 500:

Traceback (most recent call last):
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1816, in full_dispatch_request
    return self.finalize_request(rv)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1831, in finalize_request
    response = self.make_response(rv)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1982, in make_response
    reraise(TypeError, new_error, sys.exc_info()[2])
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/_compat.py", line 34, in reraise
    raise value.with_traceback(tb)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1974, in make_response
rv = self.response_class.force_type(rv, request.environ)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/werkzeug/wrappers.py", line 921, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/werkzeug/test.py", line 923, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable

The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict. 127.0.0.1 - - [29/Oct/2018 07:53:48] "POST /signUpUser HTTP/1.1" 500 -

It seems that the server code is not correctly retrieving the data or that there is a problem with the way that the data was converted to a string by JSON.stringify. I have read many others with the same problem, and have tried the solutions on stack overflow, but only get Error 400.

I tried to send a javascript dictionary to python-flask via ajax, using another approach and it works perfectly. In case the problem is that the server does not find the data (it is most likely), you can take inspiration from the approach that I describe (which seems the simplest in my opinion)

My configuration is different, you can see this discussion or this link for more information.

1. On the HTML side:

Respectively Loading jquery and adding a dynamic path to my site:

<script type=text/javascript src="{{url_for('static', filename='jquery.js') }}"> </script>

<script type=text/javascript>$SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; </script>

2. On the Jquery side:

$(function(){
    $('.btn#submit').bind('click', function(){
        var dict = {};
        dict.key1 = "value1";
        dict.key2 = "value2";

        new_dict = JSON.stringify(dict);

        $.getJSON($SCRIPT_ROOT + '/_submission', {
            dict: new_dict,
        },function(data){
            alert("Data from flask" + data.new_dict_flask);
        });
    });
});

3. On the Flask side:

@app.route('/_submission')
def submission():
    new_dict_flask = request.args.get('dict')
    return jsonify(new_dict_flask=new_dict_flask)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM