如何使用 Python 请求发布 JSON 数据?
- 2024-11-26 08:36:00
- admin 原创
- 228
问题描述:
我需要将 JSON 从客户端发布到服务器。我使用的是 Python 2.7.1 和 simplejson。客户端使用的是 Requests。服务器是 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())
有什么想法吗?
解决方案 1:
从 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'}
解决方案 2:
事实证明我遗漏了标题信息。以下内容有效:
import requests
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)
解决方案 3:
从请求 2.4.2(https://pypi.python.org/pypi/requests)开始,支持“json”参数。无需指定“Content-Type”。因此,较短的版本:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
解决方案 4:
data
您需要使用//之间json
的哪个参数files
取决于名为的请求标头Content-Type
(您可以通过浏览器的开发人员工具检查这一点)。
当 为 时Content-Type
,application/x-www-form-urlencoded
使用data=
:
requests.post(url, data=json_obj)
当 为 时Content-Type
,application/json
您可以直接使用json=
,也可以使用data=
并自行设置Content-Type
:
requests.post(url, json=json_obj)
requests.post(url, data=jsonstr, headers={"Content-Type":"application/json"})
当 为 时Content-Type
,multipart/form-data
它用于上传文件,因此使用files=
:
requests.post(url, files=xxxx)
解决方案 5:
比较好的办法是:
url = "http://xxx.xxxx.xx"
data = {
"cardno": "6248889874650987",
"systemIdentify": "s08",
"sourceChannel": 12
}
resp = requests.post(url, json=data)
解决方案 6:
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)
解决方案 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})
服务器:
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'}
解决方案 8:
目前,requests
您可以传入任何可转储为有效 JSON 的数据结构以及参数,而json
不仅仅是字典(正如 Zeyang Lin 的答案错误地声称的那样)。
import requests
r = requests.post('http://httpbin.org/post', json=[1, 2, {"a": 3}])
如果您需要对响应中的元素进行排序,这尤其有用。
解决方案 9:
总是建议我们需要能够读取 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
解决方案 10:
我用这种方式解决了:
from flask import Flask, request
from flask_restful import Resource, Api
req = request.json
if not req :
req = request.form
req['value']