python - 使用Python请求发布JSON

标签 python json python-requests cherrypy

我需要将JSON从客户端发布到服务器。我正在使用Python 2.7.1和simplejson。客户端正在使用请求。服务器是CherryPy。我可以从服务器获取硬编码的JSON(代码未显示),但是当我尝试将JSON POST到服务器时,出现“ 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())


有任何想法吗?

最佳答案

从Requests 2.4.2及更高版本开始,您可以在调用中使用'json'参数,从而使其更简单。

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}


编辑:此功能已添加到官方文档中。您可以在这里查看:Requests documentation

关于python - 使用Python请求发布JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48632977/

相关文章:

python - 在 Python 中打包旧版 Fortran。可以使用 setuptools 和 numpy.distutils 吗?

python - 如何从 Selenium 浏览器加载 session 和 cookie 到 Python 中的请求库?

python - 将 curl 命令映射到相等的 python 请求函数

javascript - 在 JSON 对象内发送函数(带参数)

python - 解析多部分/表单数据,从请求后接收

python - 获取文件最后一次在python中编辑的时间

python - 设置 psycopg2 时出现问题(PostGreSQL/python 数据库)

Python Flask 从像 render_template 这样的变量渲染文本

ASP.NET MVC 中的 JQuery Datatable 插件数据绑定(bind)

java - JSONException : no value for data