我一直在尝试使用我的python代码将SQL查询数据从运行python的客户端传输到运行PHP的Web服务器,然后将该数据输入到MySQL数据库中。
以下是模拟单行的python测试代码:
#!/usr/bin/python
import requests
import json
url = 'http://192.168.240.182/insert_from_json.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":5,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=dict(payload=json.dumps(payload)), headers=headers)
print response
以下是服务器端的PHP脚本:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload']
//$payload = '{"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}';
$payload_array = json_decode($payload_dump,true);
//get the data_payload details
$device = $payload_array['device'];
$type = $payload_array['data_type'];
$zone = $payload_array['zone'];
$sample = $payload_array['sample'];
$count = $payload_array['count'];
$time = $payload_array['time_stamp'];
$sql = "INSERT INTO data(device, data_type, zone, sample, count, time_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
如果我注释掉$ payload_dump而改为使用$ payload并运行脚本,则正确添加行。但是当我在客户端上调用python脚本时,我得到一个“响应200”但是没有添加记录。我在python中的JSON字符串格式不正确或者我没有正确传递值。
1)python代码的语法/过程是什么,可以让我看到PHP代码实际收到的内容。 (即将“$ payload_dump”变量内容转换为字符串并发送回python脚本?
2)如何解决上述代码?
答案 0 :(得分:1)
您的第一个问题是使用 json 标题,因为您没有发送原始json ,所以您不应该使用它:
您的数据看起来像
{payload = {'key1': 'value1',
'key2': 'value2' }
}
并且原始json数据应采用以下形式:
{'key1': 'value1',
'key2': 'value2'}
所以你需要从请求中删除标题
response = requests.post(url, data=dict(payload=json.dumps(payload)))
其次,您需要修复丢失的分号
$payload_dump = $_POST['payload']
到
$payload_dump = $_POST['payload'];
更好的解决方案
您可以使用请求直接发送json数据
response = requests.post(url, json=payload)
然后在php中用
抓住它$payload_array = json_decode(file_get_contents('php://input'), true);