【发布时间】:2022-01-23 02:09:37
【问题描述】:
我需要将一个 JSON 从客户端发送到服务器。我正在使用 Python 2.7.1 和 simplejson。客户端正在使用请求。服务器是 CherryPy。我可以从服务器获取硬编码的 JSON(代码未显示),但是当我尝试将 JSON 发布到服务器时,我得到“400 Bad Request”。
这是我的客户端代码:
data = {'sender': 'Alice',
'receiver': 'Bob',
'message': 'We did it!'}
data_json = simplejson.dumps(data)
payload = {'json_payload': data_json}
r = requests.post("http://localhost:8080", data=payload)
这是服务器代码。
class Root(object):
def __init__(self, content):
self.content = content
print self.content # this works
exposed = True
def GET(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(self.content)
def POST(self):
self.content = simplejson.loads(cherrypy.request.body.read())
有什么想法吗?
【问题讨论】:
-
我使用的是直接来自documentation 的示例的精简版本。
-
我的评论仍然有效 - CherryPy 不会使用
content参数调用类__init__方法(并且在您提供的链接中没有声明)。在他们拥有的详细示例中,用户提供了调用__init__的代码并提供了我们在此处没有看到的参数,因此当您的# this works评论相关时,我不知道您的对象处于什么状态。跨度> -
您是否要求查看创建实例的行?
-
是的,我试图启动您的示例以对其进行测试,但我不确定您是如何实例化它的。
-
代码已更改。我现在在没有额外参数的情况下创建它。
cherrypy.quickstart(Root(), '/', conf).
标签: python json python-requests cherrypy