Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve json data from a post request in Pyramid?

In Pyramid:

class ProjectorViews(Layouts):

def __init__(self, request):
    self.request = request

@view_config(renderer="json", name="updates.json", request_method="POST")
def updates_view(self):
    print self.request.params

JS:

$(function() {

    function get_updates () {
        data = JSON.stringify({'a':1});
        $.post('/updates.json', data, function(res) {
            });
        }, 'json').done(function() {

        });
    }

    get_updates();
});

The console shows self.request.params returns NestedMultiDict([('{"a":1}', u'')])

How do I get the keys and values in the NestedMultiDict object?

If I do self.request.params.getall("a"), it reports

KeyError: "Key not found: 'a'"

And if I do self.request.json_body, it reports

ValueError: No JSON object could be decoded
like image 400
Charles Gao Avatar asked Jun 24 '14 02:06

Charles Gao


1 Answers

$.post() always sends data with application/x-www-form-urlencoded content type. Use $.ajax() to send the data with correct content type:

$.ajax({
  url: url,
  type: "POST",
  data: data,
  contentType: "application/json; charset=utf-8",
  dataType: "json"
}).done(...);

On the Pyramid side request.json_body is the correct way to access... well, JSON body of the request.

like image 123
Sergey Avatar answered Nov 15 '22 08:11

Sergey