Python页面未渲染

2 投票
1 回答
905 浏览
提问于 2025-04-17 14:39

我创建了一个CGIHTTPServer,运行得很好,但有个问题就是不管我怎么做,Python页面总是无法正常显示,浏览器里只显示源代码。

pyhttpd.py

#!/usr/bin/python
import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
    cgi_directories = [""]
PORT = 8080
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()

cgi-bin/hello.py

#!/usr/bin/python
print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello</title></head>'
print '<body>'
print '<h2>Hello World</h2>'
print '</body></html>'

http://some.ip.address:8080/cgi-bin/hello.py:

#!/usr/bin/python
print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello</title></head>'
print '<body>'
print '<h2>Hello World</h2>'
print '</body></html>'

我已经把所有文件的权限设置为可执行,.html文件可以正常显示,即使把文件移回服务器运行的根文件夹也没有改变结果。我尝试过以root用户和普通用户运行,结果完全一样。

我试着在网上搜索“python页面不显示”,但没有找到任何有用的信息!

编辑

我还尝试过运行一个更简单的服务器,没有任何覆盖设置,但结果还是一样,Python代码从来没有被渲染:

pyserv.py

#!/usr/bin/python
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
serve = HTTPServer(("",80),CGIHTTPRequestHandler)
serve.serve_forever()

1 个回答

0

我觉得你遇到这个问题是因为你修改了 cgi_directories 的设置。

相关的文档部分提到:

“这个默认值是 ['/cgi-bin', '/htbin'],表示这些目录被视为包含 CGI 脚本的地方。”

你可以把你的脚本放在根目录,或者去掉对 cgi_directories 的修改,然后把脚本放在 /cgi-bin 目录里。

这里有一个不错的链接,逐行描述了类似的简单设置:https://pointlessprogramming.wordpress.com/2011/02/13/python-cgi-tutorial-1/

更新:

根据上面页面的一个 评论,设置 cgi_directories = [""] 会导致禁用 CGI 目录功能。相反,应该设置 cgi_directories = ["/"],这样就把它设置为当前目录。

撰写回答