Python ';请求';将数据从raspberry pi发送到web上的数据库并不';行不通

Python ';请求';将数据从raspberry pi发送到web上的数据库并不';行不通,python,php,python-requests,Python,Php,Python Requests,在我的项目中,我使用的是树莓pi,在使用函数conv_aqi()处理传感器的值后,应该将它们发送到Webhost上托管的数据库中,以便每个人都能看到它们。代码不会产生错误,但数据库中缺少值。我试图传递那些值是json。 这是python脚本: import requests def sendDatatoServer(): url = 'https://*******.000webhostapp.com/api/insert.php' data = { 'aqi_2_5'

在我的项目中,我使用的是树莓pi,在使用函数conv_aqi()处理传感器的值后,应该将它们发送到Webhost上托管的数据库中,以便每个人都能看到它们。代码不会产生错误,但数据库中缺少值。我试图传递那些值是json。 这是python脚本:

import requests
def sendDatatoServer():
url = 'https://*******.000webhostapp.com/api/insert.php'

data = {
            'aqi_2_5' : 'conv_aqi(pmt_2_5)',
            'aqi_10' : 'conv_aqi(pmt_10)',
        }

print(data)
res = requests.post(url, data)
print(res.text)

sendDatatoServer()
其中,000webhost上的insert.php如下所示:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
//Creating Array for JSON response
$response = array();

// Check if we got the field from the user
if (isset($_GET['AQI_2_5']) && isset($_GET['AQI_10'])) {

    $AQI_2_5 = $_GET['AQI_2_5'];
    $AQI_10 = $_GET['AQI_10'];

    // Include data base connect class
    $filepath = realpath (dirname(__FILE__));
    require_once($filepath."/db_connect.php");

    // Connecting to database 
    $db = new DB_CONNECT();

    // Fire SQL query to insert data in sensorData
    $result = mysql_query("INSERT INTO sensorData(AQI_2_5,AQI_10) VALUES('$AQI_2_5','$AQI_10')");

    // Check for succesfull execution of query
    if ($result) {
        // successfully inserted 
        $response["success"] = 1;
        $response["message"] = "Data from sensor successfully created.";

        // Show JSON response
        echo json_encode($response);
    } else {
        // Failed to insert data in database
        $response["success"] = 0;
        $response["message"] = "Something went wrong";

        // Show JSON response
        echo json_encode($response);
    }
} else {
    // If required parameter is missing
    $response["success"] = 0;
    $response["message"] = "Parameter(s) are missing. Please check the request";

    // Show JSON response
    echo json_encode($response);
}
?>

您的Python代码正在使用HTTP POST发送正文中的数据,但您的
insert.php
已编写为从GET请求中获取查询字符串参数

最简单的方法是使用GET和Request的params属性更改Python代码以传递查询字符串参数:

res = requests.get(url, params=data)

万分感谢!它现在的工作原理是将数据发送到数据库。但是,我希望发送conv_aqi()函数的结果。虽然我在db上找到的是确切的字符串“conv_-aqi(pmt_2_5)”和“conv_-aqi(pmt_10)”,因此它将值视为字符串,但我想在那里找到conv_-aqi()@purpleberries产生的数字,我想你几乎已经回答了你自己的问题——“确切的字符串”。您需要了解一些编程原理,因为PHP和Python都有相同的引用文本和函数调用的概念。是的,最终我能够传递值,并且可以工作,我对json也不熟悉。谢谢你让我走上了正确的道路!这回答了你的问题吗@达曼,不,这篇文章是用Python写的,但是用PHP写的