【问题标题】:CGI script with Python - Testing browser on local server使用 Python 编写 CGI 脚本 - 在本地服务器上测试浏览器
【发布时间】:2013-12-05 18:19:46
【问题描述】:

我正在尝试在 Windows 机器上本地测试 CGI Python 脚本。
我遵循了一个教程,所以它非常简单。这是我的 Python 脚本(名为 test_cgi.py,位于 cgi-bin 目录中)。

print "Content-type: text/html"
print "<html>"
print "<title>Test CGI</title>"
print "<body>"
print "<p>Hello World!</p>"
print "</body>"
print "</html>"

这是另一个启动服务器的脚本:

import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()  ## This line enables CGI error reporting

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = [""]

httpd = server(server_address, handler)
httpd.serve_forever()

启动服务器后,当我导航到http://localhost:8000/test_cgi.py 时,浏览器不会显示 HTML 内容,而是显示脚本的整个内容。有什么想法吗?

  1. 是的,我所有的文件都有可执行权限。
  2. 是的,我也尝试从命令行执行 python -m CGIHTTPServer。这成功启动了服务器,我的脚本也是如此。 :(

【问题讨论】:

  • Aside:您的脚本有错误。您需要在“Content-type”行之后打印一个空行。

标签: python windows command-line cgi


【解决方案1】:

想通了——我在 CGI 脚本的开头缺少解释器行。

【讨论】:

    【解决方案2】:

    您需要更改handler.cgi_directories 以指向包含cgi 脚本的目录。

    假设您已将文件存储在名为cgi-bin 的文件夹中,则以下内容应该可以解决问题:

    handler.cgi_directories = ['/cgi']

    【讨论】:

    • 尝试更改为 '/cgi' 和 '/cgi-bin' 无济于事。 :( 仍然显示整个脚本。
    【解决方案3】:

    您已经使用&lt;some-path&gt;\cgi-bin 的当前工作目录启动了您的服务器。这对 CGIHTTPServer 不太适用。相反,从更高的一级开始(即&lt;some-path&gt;)。

    还有:

    • 不要同时设置 cgi_directories,默认值会起作用。
    • 将浏览器指向http://localhost:8000/cgi-bin/test_cgi.py

    【讨论】:

    • 我按照你说的做了,并开始了更高的级别。我还导航到您建议的链接,它没有给我 404,但它仍在打印页面的所有内容。这真让我抓狂!还是谢谢。
    • IN 除了这两件事,你必须不要设置.cgi_directories
    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 2012-11-15
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多