执行CGI Python 脚本后,我如何return 自动进入我的主页?

After a CGI Python script is executed, how can I return automatically to my homepage?

我一直在玩网络服务器并使用 CGI 模块调用 Python 例程。这很有挑战性,但效果很好 :)

我的问题是在 Python 脚本执行后,我想在我的脚本中引入一个例程来再次重定向到我的主页。

我在这个论坛上看到过这样的问题,大多数情况下的答案是:使用命令行print("Location:http://your_page"),但我已经试过了,但对我的情况不起作用。

在下一段中我将尝试解释我的整个"mini project"然后我让你看看我的代码。

通过互联网远程控制无线家庭系统。语言Python和PHP,还有Linux知识O.S。

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 代码中插入什么才能返回我的主页?

谢谢你们,非常感谢你们的时间和帮助。

注:我用的是Python3.

如果您想打印自己的输出 重定向,您需要在响应中发出一段简单的 javascript 来执行重定向。

如果您根本不需要 CGI 的输出,则需要在打印终止 header 的双 \n\n 之前打印位置:header。您还需要添加 "pseudo" header 状态:以设置 301 或 302 响应代码。