【发布时间】:2017-12-02 21:18:30
【问题描述】:
我一直在使用 Web 服务器并使用 CGI 模块调用 Python 例程。这很有挑战性,但效果很好:)
我的问题是在 Python 脚本执行之后,我想在我的脚本中引入一个例程来再次重定向到我的主页。
我在这个论坛上看到过类似这样的问题,大多数情况下的答案是:使用命令行print("Location:http://your_page"),但我已经尝试过了,在我的情况下不起作用。
在下一段中,我将尝试解释我的整个“迷你项目”,然后让您查看我的代码。
通过互联网远程控制无线家庭系统。语言Python和PHP,还有Linux知识O.S.
此项目的目的是单击网页上的按钮(互联网连接)打开和关闭 LED。 LED 位于家中某处的无线模块中。
设置在 BeagleBone Black (Debian O.S.) 上运行的 Apache2 Web 服务器。 Beagle Bone Black 通过 UTP 电缆连接到 LAN。
将 ESP32 模块编程为 TCP 服务器并连接到 Wi-Fi (LAN)。
将 Python 脚本编程为 CGI 模块,以执行与 ESP32 模块的 TCP 客户端连接,并命令打开然后关闭 LED。该脚本在网页中单击按钮时执行。
在调制解调器/路由器上设置端口转发以允许从 Internet 访问 Web 服务器。
index.html(主页)
<!DOCTYPE html>
<html>
<head>
<title>Web Server MReyesP!</title>
<style>
.button {
padding: 15px 25px;
font-size: 24px;
text-align: center;
cursor: pointer;
outline: none;
color: #fff;
background-color: #4CAF50;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
}
.button:hover {background-color: #3e8e41}
.button:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
</head>
<body>
<h1>Success! The Web Server is working :)</h1>
<h2>Click the Button to run - "LED On/Off program"</h2>
<input class=button onClick="location.href='http://my_web_page.net/cgi-bin/TCPC$
</body>
</html>
这是我生成的主页。 Home page
python_script.py
#!/usr/bin/python3
import socket
import time
import cgitb
cgitb.enable()
print("Content-type: text/html\n\n")
print("<html>\n<body>")
print("<div style=\"with:100%; font-size: 40px; font-weight bold; text-align: c$
print("The LED was turned On and after 2 seconds was turned Off")
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip="192.168.2.112"
port=1234
address=(ip,port)
client.connect(address)
data = 'led_on'
client.sendall(data.encode('utf-8'))
time.sleep(2)
data = 'led_off'
client.sendall(data.encode('utf-8'))
client.close()
print("Location: http://my_web_page.net/\n")
print("</div>\n</body>\n</html>")
因此,我的 Python 脚本执行了例程,但没有重定向回我的主页。您可以在下一张图片中自己看到结果。此网页将永久保留。
你有什么想法吗?我必须在我的 Python 代码中插入什么才能返回我的主页?
谢谢大家,非常感谢您的时间和帮助。
注意:我使用的是 Python 3。
【问题讨论】:
-
一种简单的方法是让您的 CGI 脚本重写页面,以及您想要显示的任何额外信息(如当前 LED 状态)。 This old answer of mine 展示了另一种可能为您工作的方式。抱歉,它在 Python 2 中,但这应该很容易修复。 FWIW,CGI 这些天被认为是非常过时的,但我想它对于简单的东西仍然很方便。但是对于不那么简单的东西,它很快就会变得痛苦。 ;)
-
<input class=button onClick="location.href='http://my_web_page.net/cgi-bin/TCPC$
标签: php python linux apache2 cgi