How to receive JSON in a POST request in CherryPy?

Viewed 42686

How to receive JSON from POST requests in CherryPy?

I've been to this page, and though it does a good job explaining the API, its parameters, and what it does; I can't seem to figure out how to use them to parse the incoming JSON into an object.

Here's what I have so far:



import cherrypy
import json

from web.models.card import card
from web.models.session import getSession
from web.controllers.error import formatEx, handle_error

class CardRequestHandler(object):

    @cherrypy.expose
    def update(self, **jsonText):
        db = getSession()
        result = {"operation" : "update", "result" : "success" }
        try:
            u = json.loads(jsonText)
            c = db.query(card).filter(card.id == u.id)
            c.name = u.name
            c.content = u.content
            rzSession.commit()
        except:
            result["result"] = { "exception" : formatEx() }
        return json.dumps(result)

And, here's my jquery call to make the post


function Update(el){
    el = jq(el); // makes sure that this is a jquery object

    var pc = el.parent().parent();
    pc = ToJSON(pc);

    //$.ajaxSetup({ scriptCharset : "utf-8" });
    $.post( "http://localhost/wsgi/raspberry/card/update", pc,
            function(data){
                alert("Hello Update Response: " + data);
            }, 
            "json");
}

function ToJSON(h){
    h = jq(h);
    return { 
        "id" : h.attr("id"), 
        "name" : h.get(0).innerText, 
        "content" : h.find(".Content").get(0).innerText
    };
}
3 Answers

I found the @cherrypy.tools.json_in() way not very clean since it forces you to use cherrypy.request.json. Instead, the following decorator tries to mimic GET parameters.

The following helps this.

NOTE: This assumes you want to return JSON:

def uses_json(func):

    @functools.wraps(func)
    @cherrypy.tools.accept(media="application/json")
    def wrapper(*args, **kwargs):

        cherrypy.serving.response.headers['Content-Type'] = "application/json"

        kwargs = dict(kwargs)

        try:
            body = cherrypy.request.body.read()
            kwargs.update(json.loads(body))
        except TypeError:
            pass

        return json.dumps(func(*args, **kwargs)).encode('utf8')

    return wrapper

example:

 {"foo": "bar"}

get's translated into

 class Root(object): 
     ...
 
     @cherrypy.expose
     @uses_json
     def endpoint(self, foo):
         ....
Related