我做了简单的服务器。
该服务器正在返回原始数据。 因此,当我在 Chrome Extension to Server 中使用 ReSTLet Client 时,我可以返回我的 json post 数据。
但是,Python Requests 模块是没有返回的。
我认为请求
没有发送数据。
在 PHP 中:
<?php
print_r($_POST);
?>
在Python中:
try:
task = self.q.get_nowait()
# json_data = json.dumps(task)
if 'picture' in task['data']:
filename = task['data']['picture']
else:
filename = ''
try:
task['uuid'] = self.uuid
if filename == '':
url = 'http://server_domin/upload_nopic.php'
data = json.dumps(task)
print('task: ' + data)
r = requests.post(url, data=data)
print("Response: %s" % r.json())
else:
url = 'http://server_domin/upload.php'
files = {'file': open('./images/' + filename, 'rb')}
print('task: ' + json.dumps(task))
r = requests.post(url, files=files, data=json.dumps(task))
print("Response: %s" % r.json())
# print("Response: %s" % str(r.text()))
except Exception as ex:
print("Upload Failure. ", filename, ex)
traceback.print_stack()
traceback.print_exc()
except queues.QueueEmpty:
pass
我在发送前检查了数据(变量),并在发送后检查了响应。 数据保存正常,但响应收到空数据。
在变量数据
中:
{
"data": {
"utc": 1563862224,
"accel": {
"ax": -2.3630770385742186,
"ay": 6.636727001953124,
"az": 6.009446166992187
},
"gyro": {
"gx": -4.137404580152672,
"gy": -0.1297709923664122,
"gz": 0.2366412213740458
},
"angle": {
"ax": -14.785298705742603,
"ay": 45.78478003457668,
"az": 49.535035853061935
},
"temp": 26.459411764705884
},
"uuid": "ac2bbe96-5c2d-b960-6b88-40693bfb6a39"
}
在requests.text()
中:
'' or Array()
最佳答案
远程服务器可能需要 JSON 作为输入。
既然你使用
data = json.dumps(task)
requests.post(url, data=data)
和
requests.post(url, files=files, data=json.dumps(task))
如果不设置 Content-Type: application/json
header ,远程服务器可能无法理解您的 HTTP 请求。
当您想要发送 JSON 时,请使用 json=data
,而不是 data=data
。 It will set自动适合您的Content-Type
。
示例:
data = {
"uuid": "ac2bbe96-5c2d-b960-6b88-40693bfb6a39",
"utc": 1563862224
# ... other data
}
r = requests.post(url, json=data)
print(r.status_code, r.text) # it is always a good idea to check response HTTP status code
关于python - 为什么请求没有发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57157992/