如何在 Windows 10 上的 Python 3.5 中设置简单的 HTTP 服务器?

How to set up simple HTTP server in Python 3.5 on Windows 10?

我正在使用 python 3.5 IDLE,windows 10 和 edge 作为浏览器。在简单的 HTTP 服务器上执行以下简单代码时,我遇到了问题。问题是它只是在删除 HTML 选项卡后显示代码,而不是显示“Hello World!这是我的第一个 CGI 程序”。 我是否遗漏了环境变量等设置中的任何内容?

代码:

import cgi, cgitb
print ("Content-type:text/html\n\n")
print ('<html>')
print ('<head>')
print ('<title>Hello Word - First CGI Program</title>')
print ('</head>')
print ('<body>')
print ('<h2>Hello World! This is my first CGI program</h2>')
print ('</body>')
print ('</html>')

我已经能够让您编写的代码正常工作,所以这可能是您的调用环境中的问题。

如果您看到 cgi 文档的这一部分:https://docs.python.org/3/library/cgi.html 那么

If it’s installed in the standard cgi-bin directory, it should be possible to send it a request by entering a URL into your browser of the form:

http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home

以及此处 python HTTP 服务器文档的 cgi 部分:https://docs.python.org/3/library/http.server.html#http.server.CGIHTTPRequestHandler

cgi_directories

This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts.

那么我们需要的是一定的文件夹结构,如:

cgi-test
 |
 +-- cgi-bin
    |
    +-- test.py

test.py 包含您上面的代码。

现在启动 python HTTP 服务器导航到您的封闭文件夹(即 cgi-test)并输入 python -m http.server --cgi 8000 并假设您的 python 可执行文件在您的系统上路径你应该得到这样的回应:Serving HTTP on 0.0.0.0 port 8000 ...

最后使用浏览器导航到 http://localhost:8000/cgi-bin/test.py 以查看呈现的页面。

注意: cgi-test可以是任何东西,例如C:\Users\Username\Website, D:\MyServer\ ...

注意 2: 如果我将 test.py 文件向上移动一层到 cgi-test 文件夹,我得到的结果与您描述的类似(即我看到的是代码而不是呈现的页面)

注3: 我是运行 Windows 7 和 python 3.4,但希望应该是相似的足够了,您应该能够遵循相同的过程。