如何设置 Python CGI 服务器?

dln*_*385 5 html python windows cgi http

我在 Windows 上运行 Python 3.2。我想在我的机器上运行一个简单的 CGI 服务器以进行测试。这是我到目前为止所做的:

我使用以下代码创建了一个 python 程序:

import http.server
import socketserver
PORT = 8000
Handler = http.server.CGIHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

在同一文件夹中,我创建了“index.html”,一个简单的 HTML 文件。然后我运行该程序并在网络浏览器中访问http://localhost:8000/,页面成功显示。接下来,我在同一目录中创建了一个名为“hello.py”的文件,代码如下:

import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print()
print("""<html><body><p>Hello World!</p></body></html>""")
Run Code Online (Sandbox Code Playgroud)

现在,如果我访问http://localhost:8000/hello.py,我的网络浏览器会显示上面的完整代码,而不仅仅是“Hello World!”。如何让 python 在提供 CGI 代码之前执行它?

Tho*_*s K 5

查看CGIHTTPRequestHandler 的文档,其中描述了如何确定哪些文件是 CGI 脚本。

  • @dln385:我认为你想要 HTTPServer,而不是普通的 TCPServer:http://docs.python.org/py3k/library/http.server#http.server.HTTPServer (4认同)