Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CherryPy How to respond with JSON?

In my controller/request-handler, I have the following code:


def monkey(self, **kwargs):
  cherrypy.response.headers['Content-Type'] = "application/json"
  message = {"message" : "Hello World!" }
  return message
monkey.exposed = True

And, in my view, I've got this javascript:


$(function() {
  var body = document.getElementsByTagName("body")[0];
  $.ajaxSetup({ 
    scriptCharset : "utf-8",
    contentType: "application/json; charset=utf-8"
  });
  $.post("http://localhost/wsgi/raspberry/monkey", "somePostData",
    function(data) {
      try{
        var response = jQuery.parseJSON(data);
        body.innerHTML += "<span class='notify'>" + response + "</span>";
      }catch(e){ 
        body.innerHTML += "<span class='error'>" + e + "</span>";
      }
    }
  );
});

And finally, here's my problem. I get no JSON response and I'm not sure why.

Secondly, would someone be able to explain how to format data in my controller/request-handler response as a JSON response in the simplest way possible, without using tools?

like image 648
bitcycle Avatar asked Sep 04 '10 05:09

bitcycle


2 Answers

Since CherryPy 3.2 there are tools to accept/return JSON:

@cherrypy.expose
@cherrypy.tools.json_out()
def monkey(self, **params):
    return {"message": "Hello World!"}

Using json_out serializes the output and sets the appropriate Content-Type header for you.

Similarly decorating with @cherrypy.tools.json_in() can automatically accept/decode JSON post requests.

like image 95
fumanchu Avatar answered Oct 19 '22 01:10

fumanchu


Not sure what you mean by "without using tools" -- Python is "a tool", right?

With just Python and its standard library (2.6 or better), add at the top of your module

import json

and change the return statement to

return json.dumps(message)
like image 14
Alex Martelli Avatar answered Oct 19 '22 00:10

Alex Martelli