本文翻译自:Post JSON using Python Requests
I need to POST a JSON from a client to a server. 我需要将JSON从客户端发布到服务器。 I'm using Python 2.7.1 and simplejson. 我正在使用Python 2.7.1和simplejson。 The client is using Requests. 客户端正在使用请求。 The server is CherryPy. 服务器是CherryPy。 I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request". 我可以从服务器获取硬编码的JSON(代码未显示),但是当我尝试将JSON POST到服务器时,出现“ 400 Bad Request”。
Here is my client code: 这是我的客户代码:
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)
Here is the server code. 这是服务器代码。
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())
Any ideas? 有任何想法吗?
#1楼
参考:https://stackoom.com/question/eqAA/使用Python请求发布JSON
#2楼
As of Requests version 2.4.2 and onwards, you can alternatively use 'json' parameter in the call which makes it simpler. 从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'}
EDIT: This feature has been added to the official documentation. 编辑:此功能已添加到官方文档中。 You can view it here: Requests documentation 您可以在这里查看: 请求文档
#3楼
From requests 2.4.2 ( https://pypi.python.org/pypi/requests ), the "json" parameter is supported. 从请求2.4.2( https://pypi.python.org/pypi/requests )开始,支持“ json”参数。 No need to specify "Content-Type". 无需指定“ Content-Type”。 So the shorter version: 因此,较短的版本:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
#4楼
This works perfect for Python Version 3.5, If the URL contains Query String / Parameter value, 这对于Python 3.5版非常理想,如果该URL包含查询字符串/参数值,
Request URL = https://baaaah2.com/ws/rest/v1/concept/ 请求网址= https://baaaah2.com/ws/rest/v1/concept/
Parameter value = 21f6bb43 参数值= 21f6bb43
import requests
headers = {'Content-type': 'application/json'}
result = requests.post('https://baaaah2.com/ws/rest/v1/concept/21f6bb43',auth=('username', 'password'),verify=False, headers=headers)
print(result.status_code)
#5楼
Works perfectly with python 3.5+ 与python 3.5+完美搭配
client: 客户:
import requests
data = {'sender': 'Alice',
'receiver': 'Bob',
'message': 'We did it!'}
r = requests.post("http://localhost:8080", json={'json_payload': data})
server: 服务器:
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'}
#6楼
The better way is: 更好的方法是:
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)