如何從CherryPy的POST請求中接收JSON?如何在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
};
}
THX爲您發佈,這是恕我直言,最徹底的方法去做吧。 – 2013-09-25 11:10:08
'cherrypy.request'沒有屬性'json' – IAbstract 2015-03-06 23:00:29
@IAbstract檢查你是否有'''@ cherrypy.tools.json_in()'''裝飾器。 – 2015-06-10 12:19:39