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

标签 json post cherrypy

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

我去过this page ,尽管它很好地解释了 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)

还有,这是我发帖的 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
    };
}

最佳答案

Python

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

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

关于json - 如何在 CherryPy 的 POST 请求中接收 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743769/

相关文章:

javascript - 发送超过 2000 个字符的 JSON 数据

json - 为什么planet_osm_ways表中tags列的数据类型不是JSON格式?

javascript - 无法使用 jQuery 查询 JSON

javascript - jQuery 函数未提交 Ajax 请求

java - java中使用jetty发送json对象

javascript - 如何将WebRTC捕获的照片发布到服务器

python - Cherrypy 中的子页面和路由

python - Cherrypy 与 Mysql 错误 : "tuple indices must be integers, not str" when trying to add users

python - cherrypy mvc 与 mysql 问题

javascript - 如何以一种或另一种方式对从帖子返回的数据求和