Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain Flask request JSON data as dictionary?

Im struggling with JQuery ajax methods and Flask, trying to make an ajax call to retrieve some form.

My js code looks like this:

$.ajax({
       type: 'POST',
       url: '/projects/dummyName',
       data: JSON.stringify("{'ajax': 'True'}"),
       contentType: 'application/json;charset=UTF-8',
       dataType: 'html',
       success: function(responseData, textStatus, jqXHR) {
           $("#myform").text(responseData);
         },
       error: function (responseData, textStatus, errorThrown) {
           alert('Error: '+errorThrown + ". Status: "+textStatus);
       }
}); 

Basically im adding the data parameter to let the server method that this is an ajax call. But i just cant get that data in the server as a dict. Tried millon ways, im cant make it work.

This is the dummy server method:

@app.route('/projects/<name>', methods=['GET', 'POST'])
def projects(name=None):
    print(request.json)
    print(request.json['ajax'])
    if name:
        project = db.getProject(name)
        form = ProjectForm(project)

        if request.json['ajax'] == True:
            return render_template("myform.html", form=form)
        else:
            return render_template("projectView.html", form=form)
    else:
        return render_template("projects.html")

So, request.json returns a string:

{'ajax': 'True'}

Of course the app breaks when try to access json['ajax'] and I get a BAD RESPONSE error msg. I thought that would give me a python dict, because otherwise what would be the difference between request.json and request.data if both are strings.

How can i get a python dict with all the data passed in the ajax call? Does it depend on the way I define the contentType? does it depend on the use of JSON.stringify or not?

Help will be much appreciated! Thanks

like image 769
Sebastian Avatar asked Nov 13 '13 20:11

Sebastian


1 Answers

The data is being put into request.json because of the mimetype of the request. I believe you are looking for get_json.

@app.route('/projects/<name>', methods=['GET', 'POST'])
def projects(name=None):
    req_json = request.get_json()
    print(req_json['ajax'])
    if name:
        project = db.getProject(name)
        form = ProjectForm(project)

        if req_json['ajax']:
            return render_template("myform.html", form=form)
        return render_template("projectView.html", form=form)
    return render_template("projects.html")

I do not have access to my dev machine at the moment so I haven't tested this, but it should work from my understanding of the docs.

like image 127
Seberius Avatar answered Oct 21 '22 20:10

Seberius