如何在CherryPy的POST请求中接收JSON?

bit*_*cle 25 post json cherrypy

如何从CherryPy中的POST请求接收JSON?

我去过这个页面,虽然它很好地解释了API,它的参数以及它的作用; 我似乎无法弄清楚如何使用它们将传入的JSON解析为一个对象.

这是我到目前为止所拥有的:



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)
Run Code Online (Sandbox Code Playgroud)

而且,这是我的jquery电话来发帖


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
    };
}
Run Code Online (Sandbox Code Playgroud)

小智 41

蟒蛇

import cherrypy

class Root:

    @cherrypy.expose
    @cherrypy.tools.json_out()
    @cherrypy.tools.json_in()
    def my_route(self):

        result = {"operation": "request", "result": "success"}

        input_json = cherrypy.request.json
        value = input_json["my_key"]

        # Responses are serialized to JSON (because of the json_out decorator)
        return result
Run Code Online (Sandbox Code Playgroud)

JavaScript的

//assuming that you're using jQuery

var myObject = { "my_key": "my_value" };

$.ajax({
    type: "POST",
    url: "my_route",
    data: JSON.stringify(myObject),
    contentType: 'application/json',
    dataType: 'json',
    error: function() {
        alert("error");
    },
    success: function() {
        alert("success");
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 对你来说,这是恕我直言,这是最干净的方式. (2认同)
  • @IAbstract检查你有```@ cherrypy.tools.json_in()``装饰器. (2认同)

fum*_*chu 30

工作范例:

import cherrypy
import simplejson

class Root(object):

    @cherrypy.expose
    def update(self):
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        body = simplejson.loads(rawbody)
        # do_something_with(body)
        return "Updated %r." % (body,)

    @cherrypy.expose
    def index(self):
        return """
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
function Update() {
    $.ajax({
      type: 'POST',
      url: "update",
      contentType: "application/json",
      processData: false,
      data: $('#updatebox').val(),
      success: function(data) {alert(data);},
      dataType: "text"
    });
}
</script>
<body>
<input type='textbox' id='updatebox' value='{}' size='20' />
<input type='submit' value='Update' onClick='Update(); return false' />
</body>
</html>
"""

cherrypy.quickstart(Root())
Run Code Online (Sandbox Code Playgroud)

您链接的文档描述了3.2版本中新增的几个CherryPy工具.该json_in工具基本上完成了上述操作,更严格,并使用3.2中的新身体处理API.

需要注意的一件重要事情是,jQuery的post功能似乎无法发送JSON(只接收它).该dataType参数指定了您希望XmlHTTPRequest 接收的数据类型,而不是它将发送的类型,并且似乎没有可用于指定要发送的类型的参数.使用ajax()而是允许您指定.