树莓派使用HTTP调用Python或者Bash脚本

这里在树莓派下使用HTML网页和轻量级web服务器Lighttpd直接调用python或者bash脚本,而并不使用Django,Flask等Web框架。

这里我们实现通过网页端对一个LED灯进行点亮和关闭操作

第一步: 需要的硬件材料

  • 树莓派4一个
  • LED灯一个,杜邦线若干

第二步:安装Lighttpd轻量级web 服务器

Lighttpd是一个轻量级的WEB服务器,安全,快速,灵活,占用极低的内存,适合树莓派这样的ARM架构的设备使用,类似的其他服务器还有Apache,Nginx等。我们将使用Lightttpd 的CGI技术来调用脚本。

安装Lightttpd:

  • sudo apt update
  • sudo apt install lighttpd

使用systemctl status lighttpd可以看到lighttp的已经开始运行


树莓派使用HTTP调用Python或者Bash脚本


对lighttpd进行配置:

启用cgi和fastcgi,我们将会借助cgi技术实现http网页调用树莓派下的脚本

sudo lighttpd-enable-mod cgi

sudo lighttpd-enable-mod fastcgi

CGI是Common Gateway Interface ,是web服务器调用服务器脚本常使用的技术

默认的lighttpd的配置文件的路径是:

/etc/lighttpd

树莓派使用HTTP调用Python或者Bash脚本

在lighttpd.conf中可以对服务器的站点路径 ,端口等进行配置,这里我们使用默认的站点路径/var/www/html

配置cgi:


树莓派使用HTTP调用Python或者Bash脚本

打开/etc/lighttpd/conf-enabled/10-cig.conf 修改为如下的配置

# /usr/share/doc/lighttpd/cgi.txt
server.modules += ( "mod_cgi" )
$HTTP["url"] =~ "^/cgi-bin/" {
alias.url += ( "/cgi-bin/" => "/var/www/html/cgi-bin/" )
cgi.assign = (".cgi" => "/usr/bin/bash",".py" => "/usr/bin/python3")
}

其中alias.url += ( "/cgi-bin/" => "/var/www/html/cgi-bin/" ) 制定了cgi寻找的路径实在

/var/www/html/cgi-bin/,因此在/var/www/html/文件夹下新建cgi-bin文件夹

sudo mkdir /var/www/html/

配置文件中cgi.assign = (".cgi" => "/usr/bin/bash",".py" => "/usr/bin/python3") ,是说

.py 的脚本使用python3来执行,.cgi的脚本这里我们定义为bash脚本,类似的你可以定义perl脚本等。

第三步:创建脚本

树莓派使用HTTP调用Python或者Bash脚本

树莓派下默认安装了WringPi,可以对树莓派的GPIO进行操作,这里我们使用第12引脚进行led的操作

树莓派使用HTTP调用Python或者Bash脚本

在/var/www/html/cgi-bin目录下新建ledon.cgi和ledoff.cgi两个脚本

cd /var/www/html/cgi-bin
touch ledon.cgi  ledon.cgi
chmod 755  ./ledon.cgi  ./ledon.cgi

ledon.cgi实现点亮led,内容为

#!/bin/bash
gpio -g mode 18 out
gpio -g write 18 0

ledon.cgi实现关闭led ,内容为

#!/bin/bash
gpio -g mode 18 out
gpio -g write 18 1

创建一个python脚本test.py

print("Content-Type: text/html

") 
timeStr = time.strftime("%c") # obtains current time
htmlFormat = """

The Time Now

The current Central date and time is:

""" print(htmlFormat+str(timeStr))

注意这里如果需要使用python代码操作gpio等外围硬件,会因为lighttpd默认用户www-data的权限问题无法成功,需要将lighttpd的用户修改为用户pi

我们这里使用bash脚本操作led等,python脚本返回数据不存在权限问题

第四步:创建HTML网页调用脚本

在路径/var/www/html/下新建index.html

cd /var/www/html/
sudo touch index.html
sudo chmod 777 index.html

index.html 的内容如下




Welcome You!



Welcome to lighttpd!



这里通过XMLHttpRequest 实现原生GET请求,XMLHttpRequest一开始只是微软浏览器提供的一个接口,后来各大浏览器纷纷效仿也提供了这个接口,再后来W3C对它进行了标准化,提出了XMLHttpRequest标准。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章