简体   繁体   English

CherryPy如何用JSON回复?

[英]CherryPy How to respond with JSON?

In my controller/request-handler, I have the following code: 在我的controller / request-handler中,我有以下代码:


def monkey(self, **kwargs):
  cherrypy.response.headers['Content-Type'] = "application/json"
  message = {"message" : "Hello World!" }
  return message
monkey.exposed = True

And, in my view, I've got this javascript: 而且,在我看来,我有这个javascript:


$(function() {
  var body = document.getElementsByTagName("body")[0];
  $.ajaxSetup({ 
    scriptCharset : "utf-8",
    contentType: "application/json; charset=utf-8"
  });
  $.post("http://localhost/wsgi/raspberry/monkey", "somePostData",
    function(data) {
      try{
        var response = jQuery.parseJSON(data);
        body.innerHTML += "<span class='notify'>" + response + "</span>";
      }catch(e){ 
        body.innerHTML += "<span class='error'>" + e + "</span>";
      }
    }
  );
});

And finally, here's my problem. 最后,这是我的问题。 I get no JSON response and I'm not sure why. 我没有得到JSON响应,我不知道为什么。

Secondly, would someone be able to explain how to format data in my controller/request-handler response as a JSON response in the simplest way possible, without using tools? 其次,有人能够在不使用工具的情况下,以最简单的方式解释如何将控制器/请求处理程序响应中的数据格式化为JSON响应吗?

Since CherryPy 3.2 there are tools to accept/return JSON: 从CherryPy 3.2开始,有接受/返回JSON的工具:

@cherrypy.expose
@cherrypy.tools.json_out()
def monkey(self, **params):
    return {"message": "Hello World!"}

Using json_out serializes the output and sets the appropriate Content-Type header for you. 使用json_out序列化输出并为您设置适当的Content-Type标头。

Similarly decorating with @cherrypy.tools.json_in() can automatically accept/decode JSON post requests. 类似地,使用@cherrypy.tools.json_in()进行装饰可以自动接受/解码JSON后置请求。

Not sure what you mean by "without using tools" -- Python is "a tool", right? 不确定你的意思是“不使用工具” - Python “工具”,对吗?

With just Python and its standard library (2.6 or better), add at the top of your module 只需使用Python及其标准库(2.6或更高版本),就可以在模块的顶部添加

import json

and change the return statement to 并将return语句更改为

return json.dumps(message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM