Reputation: 55
I made simply server.
This Server is return post raw data. So, When I use Restlet Client in Chrome Extension to Server, I can return my json post data.
But, Python Requests module is no return.
I think requests
did not send data.
Python 3.6.8 Requests 2.21.0 PHP 7
In PHP:
<?php
print_r($_POST);
?>
In 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
I checked the data(variable) just before sending and the response after sending. data is saved normally, but response recieved empty data.
In Variable data
:
{
"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"
}
In requests.text()
:
'' or Array()
Upvotes: 1
Views: 300
Reputation: 4483
The remote server probably wants a JSON as an input.
And since you use
data = json.dumps(task)
requests.post(url, data=data)
and
requests.post(url, files=files, data=json.dumps(task))
without setting Content-Type: application/json
header, remote server may be unable to understand your HTTP request.
When you want to send a JSON, use json=data
, not data=data
. It will set appropriate Content-Type
for you automatically.
Example:
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
Upvotes: 1