Decoding JSON with python using Appengine

不问归期 提交于 2019-12-03 21:40:52

Have a look in your debugger. You receive a JSON string in your post (webapp2 multidict). You have to decode this string using json.loads, resulting in a python object.

Here is my jquery code to send and receive json :

function gaeQuery(request) {
    var url = "/query";
    var payload = {'jsondata' : JSON.stringify(request)};
    $.post(
    url, 
    payload, 
    function(response) {
        procesResponse(response);
    },  // succes response callback 
    'json',  // response contains JSON content, and will be decoded in a js object
    {
        contentType: "application/json;charset=utf-8", // send JSON content
        timeout: 20000,
        tryCount: 0,
        retryLimit: 3, // max 3 retries             
        error: function(xhr, textStatus, errorThrown) { // error handling callback
            if (textStatus === 'timeout') {
                this.tryCount++;
                if (this.tryCount <= this.retryLimit) { //try again until retryLimit
                    $.ajax(this);
                    return;
                }
                alert('We have tried ' + this.retryLimit + ' times and it is still not working. We give in. Sorry.');
                return;
            }
            if (xhr.status === 500) { // internal server error
                alert('Oops! There seems to be a server problem, please try again later.');
            } 
            else {
                alert('Oops! There was a problem, sorry.'); // something went wrong
            }
        }
    }
    );
}

OK so I managed to figure this out and thought I will post the answer that worked for me to help anyone looking for this information because the webapp2 docs are not that helpful when it comes to 'getting' posted json data.

on the client side I did the following:

var request = $.ajax({
    url: "/some/url/",
    type: "POST",
    data: JSON.stringify([{someval: val1, someval2:val2, someval3:val3}]),
    contentType: "application/json",
    dataType: 'json',
    beforeSend: function() {
        $('#loading-div').show();
    },
    complete: function(){
        $('#loading-div').hide();
    },
    success: function(response, textStatus, jqXHR){}
});

The reason I couldnt figure out the problem straight away was because of the following line which I deleted along with some commented out line which prevented the page from redirecting after posting. This was the source of all the weird, unrelated and unhelpful error messages:

event.preventDefault();

on the server side to get the json data being posted to appengine do the following:

jdata = json.loads(cgi.escape(self.request.body))
    for vals in jdata:
        val1 = vals['someval']
        val2 = vals['someval2']
        val3 = vals['someval3']

The above was the root of the problem I wasn't doing it right and without the previous line on the client side there was no way to figure it out.

Anyways once you have the data do whatever processing you need to do with it and once you are done and need to send back a json response add the following lines:

//the data would look something like this 
data = {'return_value': val1, 'return_value2': val2,
        'return_value3': val3, 'return_value4': val4}

        return_data = json.dumps(data)
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.write(return_data)

Almost forgot on the client side again to access the variables sent back from the server with jquery its very straight forward...do something like:

 success: function(response, textStatus, jqXHR){
        console.log(response.return_value);
        console.log(response.return_value2);
        console.log(response.return_value3);
 }

Hope this will help someone seeking this information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!