【发布时间】:2020-04-20 09:22:07
【问题描述】:
我正在处理一个工作项目,但遇到了一些麻烦,我有一个安装了 Ubuntu 18.04 服务器的 LAMP 服务器,在服务器端我有一个 PHP 脚本,用于实现从表格中的客户端接收到的数据通过 URl 在 MySQL 数据库中。我正在谈论的客户端是通过串行连接到 DHT22 传感器的 Raspberry Pie 3。
我现在遇到的问题是我根本没有太多使用 Python 的经验。我制作了一个脚本,可以在控制台中打印来自传感器的数据。但我不知道如何将数据从客户端发送到数据库。
如果我要使用 PHP 脚本,客户端将需要在 PHP 脚本的 URl 路径中打印数据(例如:http://192.168.0.101?temp=20.1&hum=30.2),但我希望你们能告诉我如何做到这一点,或者如果有任何方法我可以跳过整个 PHP 脚本并实现一种连接到数据库并使用 Python 脚本将数据直接打印到表中的方法。
我正在使用的 PHP 脚本:
<?php
class DBtable {
public $link='';
function __construct($temperature, $humidity) {
$this->connect();
$this->storeInDB($temperature, $humidity);
}
function connect() {
$this->link = mysqli_connect('localhost','Generic_user','Generic_passwd') or die('Cannot connect to DB');
mysqli_select_db($this->link,'DBtable') or die('Cannot choose DB.');
}
function storeInDB($temperature, $humidity) {
$query = "insert into DBtable set Hum='".$humidity."', Temp='".$temperature."'";
$result =mysqli_query($this->link,$query) or die('Errant query: '.$query);
("Data was implemented correct! Temp = '".$temperature."'°C og Hum = '".$humidity."'%'");
}
}
if($_GET['Temp'] != '' and $_GET['Hum'] != '') {
$DBtable=new DBtable($_GET['Temp'],$_GET['Hum']);
}
?>
(出于安全原因,我更改了一些信息,但我可以向您保证,我已经对其进行了测试并且可以正常工作。)
脚本最初是为 Arduino 编写的,但我无法让它工作,所以我切换到了 Raspberry 平台。
客户端上的 Python 脚本:
import Adafruit_DHT as dht
from time import sleep
DHT = 3
while True:
h,t = dht.read_retry(dht.DHT22, DHT)
print('temp={0:0.1f}*C hum={1:0.1f}%'.format(temperature, humidity))
sleep(1)
控制台的输出:
temp=20.1*C hum=30.2%
那么问题来了,我该怎么做才能将数据发送到 PHP 脚本,或者如果失败了,跳过 PHP 部分并直接使用 Python 脚本?
如果你们需要更多信息,请询问,我会尽我所能提供。谢谢!
-----更新-----
所以!我发现了一些可行的方法,我正在尝试使用Requests 来POST 数据。我正在服务器上创建一个PHP 脚本,它将接收到的数据注入到 MySQL 数据库中。然后是测试,我将向你们更新它的进展情况。
如果您有任何建议就拍吧,如果您需要更多信息或有任何问题,我仍然会在这里!
【问题讨论】:
-
要使用 PHP,您需要 Python 外部模块
requests或标准urllib.request。 - 喜欢requests.get("http://192.168.0.101?temp=20.1&hum=30.2") -
使用任何与
MySQL一起工作的Python模块直接将其发送到数据库 - 即mysql-connector-python - 请参阅Chapter 5 Connector/Python Coding Examples -
@furas 非常感谢!我去看看。
标签: python php mysql python-3.x raspberry-pi