我需要POST一个JSON从客户端到服务器。我使用的是Python 2.7.1和simplejson。客户端正在使用请求。服务器为CherryPy。我可以得到一个硬编码的JSON从服务器(代码未显示),但当我试图POST一个JSON到服务器,我得到“400坏请求”。

下面是我的客户端代码:

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())

什么好主意吗?


当前回答

在请求2.4.2 (https://pypi.python.org/pypi/requests)中,支持“json”参数。不需要指定“Content-Type”。所以简短的版本:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})

其他回答

我是这样解决的:

from flask import Flask, request
from flask_restful import Resource, Api


req = request.json
if not req :
    req = request.form
req['value']

在请求2.4.2 (https://pypi.python.org/pypi/requests)中,支持“json”参数。不需要指定“Content-Type”。所以简短的版本:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})

从Requests 2.4.2版本开始,你可以在调用中使用json=参数(接受一个字典)而不是data=(接受一个字符串):

>>> 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'}

它总是建议我们需要具备读取JSON文件并将对象解析为请求体的能力。我们不打算解析请求中的原始数据,因此下面的方法将帮助您解析它。

def POST_request():
    with open("FILE PATH", "r") as data:
        JSON_Body = data.read()
    response = requests.post(url="URL", data=JSON_Body)
    assert response.status_code == 200

适用于python 3.5+

客户:

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

服务器:

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'}