如何在 CherryPy 的 POST 请求中接收 JSON? [英] How to receive JSON in a POST request in CherryPy?

查看:28
本文介绍了如何在 CherryPy 的 POST 请求中接收 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to receive JSON from POST requests in CherryPy?

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

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.

这是我目前所拥有的:



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)

而且,这是我发布帖子的 jquery 调用

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
    };
}

推荐答案

工作示例:

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())

您链接到的文档描述了 3.2 版中新增的几个 CherryPy 工具.json_in 工具基本上完成了上面的工作,更严谨一些,并且使用了 3.2 中新的 body 处理 API.

The doc you linked to describes a couple of CherryPy Tools that are new in version 3.2. The json_in tool basically does the above, with some more rigor, and using the new body processing API in 3.2.

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

One important thing to note is that jQuery's post function doesn't seem to be able to send JSON (only receive it). The dataType argument specifies the type of data you expect the XmlHTTPRequest to receive, not the type it will send, and there doesn't seem to be an argument available for you to specify the type you want to send. Using ajax() instead allows you to specify that.

这篇关于如何在 CherryPy 的 POST 请求中接收 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆