使用Python请求发布JSON

Cha*_*s R 545 python json cherrypy python-requests

我需要将JSON从客户端POST到服务器.我正在使用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)
Run Code Online (Sandbox Code Playgroud)

这是服务器代码.

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())
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 876

从请求版本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'}
Run Code Online (Sandbox Code Playgroud)

编辑:此功能已添加到官方文档中.您可以在此处查看:请求文档

  • 我无法相信在浪费你的答案之前我浪费了多少时间.**请求**文档需要升级,`json`参数绝对没有.在我看到它之前我不得不进入Github:https://github.com/kennethreitz/requests/blob/76f7ce8a249e57df5ed1f2331a43e635895bdbba/requests/api.py (89认同)
  • 我看到了一个例子,它在发送之前获取 dict 对象并执行 json.dumps(object) 。不要这样做...它会弄乱你的 JSON。上面是完美的..你可以向它传递一个 python 对象,它会变成完美的 json。 (5认同)
  • @MydKnight查看源代码,Requests设置内容类型,然后执行[`json.dumps(your_json)`](https://github.com/psf/requests/blob/4f6c0187150af09d085c03096504934eb91c7a9e/requests/models.py#L469)并将结果从“str”转换为“bytes”。 (4认同)
  • 在找到这个答案之前,我还必须使用“data=json.dumps(...)``”,但标头中没有“Content-type: application/json``”,它将无法工作。这个 ```json=...``` 东西工作得非常完美。 (3认同)
  • 将其设置为已接受的答案,因为从 2.4.2 开始这更为惯用。请记住,对于疯狂的 unicode,这可能不起作用。 (2认同)

Cha*_*s R 345

事实证明我错过了标题信息.以下作品:

url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
Run Code Online (Sandbox Code Playgroud)

  • 在这里使用 `json.dumps` 之前,请先提醒一下。`requests` 的 `data` 参数适用于字典。无需转换为字符串。 (2认同)

ZZY*_*ZZY 57

根据请求2.4.2(https://pypi.python.org/pypi/requests),支持"json"参数.无需指定"Content-Type".所以较短的版本:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})
Run Code Online (Sandbox Code Playgroud)


小智 30

其参数之间data/ json/files你需要使用取决于命名请求头Content-Type(您可以通过浏览器的开发者工具检查)。

Content-Type是时application/x-www-form-urlencoded,使用data=

requests.post(url, data=json_obj)
Run Code Online (Sandbox Code Playgroud)

Content-Typeis 时application/json,您可以直接使用json=或使用data=并自行设置Content-Type

requests.post(url, json=json_obj)
Run Code Online (Sandbox Code Playgroud)
requests.post(url, data=jsonstr, headers={"Content-Type":"application/json"})
Run Code Online (Sandbox Code Playgroud)

Content-Typeis 时multipart/form-data,它用于上传文件,因此使用files=

requests.post(url, files=xxxx)
Run Code Online (Sandbox Code Playgroud)


小智 26

更好的方法是:

url = "http://xxx.xxxx.xx"

datas = {"cardno":"6248889874650987","systemIdentify":"s08","sourceChannel": 12}

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

rsp = requests.post(url, json=datas, headers=headers)
Run Code Online (Sandbox Code Playgroud)

  • `content-type:application/json`是多余的,因为`json =`已经暗示了这一点. (13认同)
  • “***更好的方法是***”不要在**正确答案三年后发布**错误答案。-1 (8认同)

isa*_*isa 12

headers = {"charset": "utf-8", "Content-Type": "application/json"}
url = 'http://localhost:PORT_NUM/FILE.php'

r = requests.post(url, json=YOUR_JSON_DATA, headers=headers)
print(r.text)
Run Code Online (Sandbox Code Playgroud)


小智 8

在 current 中,requests您可以使用参数传入任何转储为有效 JSON 的数据结构,而json不仅仅是字典(如 Zeyang Lin 的答案错误地声称的那样)。

import requests
r = requests.post('http://httpbin.org/post', json=[1, 2, {"a": 3}])
Run Code Online (Sandbox Code Playgroud)

如果您需要对响应中的元素进行排序,这尤其有用。


Ruh*_*wal 7

与python 3.5+完美配合

客户:

import requests
data = {'sender':   'Alice',
    'receiver': 'Bob',
    'message':  'We did it!'}
r = requests.post("http://localhost:8080", json={'json_payload': data})
Run Code Online (Sandbox Code Playgroud)

服务器:

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)

    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def POST(self):
        self.content = cherrypy.request.json
        return {'status': 'success', 'message': 'updated'}
Run Code Online (Sandbox Code Playgroud)