CherryPy How to respond with JSON?
Asked Answered
E

2

21

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?

Elf answered 4/9, 2010 at 5:14 Comment(2)
Do you know that CherryPy supplies a decorator for exposing functions? Just put @cherrypy.exposed on the line above the def monkey...Brit
Note that the correct decorator is now @cherrypy.exposeAdara
S
14

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)
Saied answered 4/9, 2010 at 5:20 Comment(5)
In Python 2.5, you can use the simplejson package.Brit
Actually, what I meant by saying "without tools" was without using decorators. I'm still getting used to python's idiosyncrasies. Yes, I have seen simplejson used, but I want to be able to do it using the base libraries first.Elf
@Sean, simplejson is just the older version of json, from before the latter was incorporated into the Python standard library. IOW, json is not any more "base" than simplejson, it's just a "packaging" decision by the PSF (specifically by the core developers of Python itself and the standard library that goes with it).Saied
"Tool" is CherryPy jargon for "plugin". There's a whole subsystem for using them and making your own: docs.cherrypy.org/dev/intro/concepts/tools.htmlAllies
with this approach, you need to call cherrypy.response.headers['Content-Type'] = 'application/json' to set the correct content type. however you shoul rather use @cherrypy.tools.json_out() insteadDryclean
A
46

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.

Allies answered 4/9, 2010 at 16:58 Comment(4)
Thanks for this. In reading Alex's post above and doing some testing on my own, I realize that your suggestion is more succinct, explicit, and readable than using JSON.dumps().Elf
CherryPy 3.2 has been released, by the way :)Allies
Here's the documentation for json_out: docs.cherrypy.org/en/latest/refman/lib/…Ventilate
The above documentation is now at cherrypy.readthedocs.org/en/latest/pkg/…Superheat
S
14

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)
Saied answered 4/9, 2010 at 5:20 Comment(5)
In Python 2.5, you can use the simplejson package.Brit
Actually, what I meant by saying "without tools" was without using decorators. I'm still getting used to python's idiosyncrasies. Yes, I have seen simplejson used, but I want to be able to do it using the base libraries first.Elf
@Sean, simplejson is just the older version of json, from before the latter was incorporated into the Python standard library. IOW, json is not any more "base" than simplejson, it's just a "packaging" decision by the PSF (specifically by the core developers of Python itself and the standard library that goes with it).Saied
"Tool" is CherryPy jargon for "plugin". There's a whole subsystem for using them and making your own: docs.cherrypy.org/dev/intro/concepts/tools.htmlAllies
with this approach, you need to call cherrypy.response.headers['Content-Type'] = 'application/json' to set the correct content type. however you shoul rather use @cherrypy.tools.json_out() insteadDryclean

© 2022 - 2024 — McMap. All rights reserved.