我如何接收带有 post 请求、json 和 cherrypy 的字典?

How do I receive a dict with a post request, json and cherrypy?

我只是想向客户端 post 请求发送响应,但我不知道如何解码响应。我总是得到一个字符串。

这是我的服务器代码:

import json
import cherryp

class Hey:

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        a = {"a": "1", "b": "2", "c": "3"}
        return json.dumps(a)

if __name__ == '__main__':
     cherrypy.quickstart(Hey())

这是我的客户端代码:

import requests
import json
headers = {'Content-type': 'application/json'}


def postServer():
    resp = requests.post("http://localhost:8080/index", headers=headers)
    return resp.json()


def test():
    response = postServer()
    print(response)


test()

您的服务器代码应如下所示:

import json
import cherrypy

class Hey:

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        a = {"a": "1", "b": "2", "c": "3"}
        return a

if __name__ == '__main__':
     cherrypy.quickstart(Hey())

json_out 会将字典转换为有效的 JSON 字符串。

此外,在您的客户端代码中,您不必 import json 即可使用 requests 中的 json 方法。