CherryPy和JSON:发送词典列表

时间:2015-07-15 13:23:50

标签: python json post cherrypy

我想从Web浏览器向运行CherryPy的服务器发送一个字典列表。 CherryPy中的代码应该接收什么?

Web浏览器中的JavaScript

var listOfDictionaries = {
    "Coordinates":
    [
        {"x":"892850686394369 ","y":"4c189d55d5a2b4d682647bfcc9e5827112abfe7c"},
        {"x":"892850686394430 ","y":"b1c8238337a3e17352718a46ca0a76a7e196adfd"}
    ]
};

$.post('drawChart', listOfDictionaries,
    function (data) {
        $("#title").html(data['title']);
    });

我通过HTTP POST发送的数据:

{"Coordinates":[{"x":"892850686394369 ","y":"4c189d55d5a2b4d682647bfcc9e5827112abfe7c"},{"x":"892850686394430 ","y":"b1c8238337a3e17352718a46ca0a76a7e196adfd"}]}

Web服务器上的CherryPy方法

@cherrypy.expose
def drawChart(self, x, y):
    cherrypy.response.headers['Content-Type'] = 'application/json'
    return json.dumps(dict(title="x: %s" x))

2 个答案:

答案 0 :(得分:0)

使用@cherrypy.tools.json_in()@cherrypy.tools.json_out()

@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def drawChart(self):
    data = cherrypy.request.json  # data = {"Coordinates":[{"x": ...
    x = [xypair["x"] for xypair in data["Coordinates"]]
    return {"title": "x[]: %s" x}

请注意,这需要CherryPy 3.2

(注意:我只在python 3上工作,可能不在python 2上工作)

答案 1 :(得分:0)

很抱歉迟到的回答,我解决了这个问题:

客户端(浏览器):

    coordinates = {'coordinates': coordinates}
    $.post('/drawChart', coordinates, function (data) {
                    createGraph((data['Coordinates']));
                });

服务器端(python):

@cherrypy.expose
def drawChart(self, coordinates):
    cherrypy.response.headers['Content-Type'] = 'application/json'
    listOfCoordiantes = randomData(coordinates)
    return json.dumps(dict(Coordinates=listOfCoordiantes))