我试图使用以下python脚本(hello.py)运行cgi webserver:
print ('Content-Type: text/html')
print
print ('<html>')
print ('<head><title>Hello from Python</title></head>')
print ('<body>')
print ('<h2>Hello from Python</h2>')
print ('</body></html>')
我把hello.py放在我运行python的dir的cgi-bin文件夹中。 在命令窗口中,我使用以下命令启动了Web服务器:
python -m http.server --bind localhost --cgi 8000
比我打开一个浏览器: http://localhost:8000/cgi-bin/hello.py
浏览器已打开,但它是空白的,没有显示任何内容,而根据脚本应该显示“来自python的Hello”。 这些是后端显示的消息,似乎没有错误。
C:\python_dir>python -m http.server --bind localhost --cgi 8000
Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) ...
127.0.0.1 - - [17/Feb/2018 15:14:41] "GET /cgi-bin/hello.py HTTP/1.1" 200 -
127.0.0.1 - - [17/Feb/2018 15:14:41] command: C:\python_dir\python.exe -u
C:\Users\user\cgi-bin\hello.py ""
127.0.0.1 - - [17/Feb/2018 15:14:41] CGI script exited OK
这是我第一次启动网络服务器,我无法弄清楚出了什么问题。
答案 0 :(得分:0)
你的脚本将所有内容作为标题内容返回,而不是像预期的那样返回正文,如快速卷曲调用所示:
curl --verbose localhost:8000/cgi-bin/hello.py
* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script output follows
< Server: SimpleHTTP/0.6 Python/3.6.4
< Date: Sat, 17 Feb 2018 20:41:26 GMT
< Content-Type: text/html
< <html>
< <head><title>Hello from Python</title></head>
< <body>
< <h2>Hello from Python</h2>
< </body></html>
* Closing connection 0
通过分隔标题和内容,服务器可以将标题与正文区分开来:
print ('Content-Type: text/html')
print ('\n')
print
...
给出:
* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script output follows
< Server: SimpleHTTP/0.6 Python/3.6.4
< Date: Sat, 17 Feb 2018 20:45:35 GMT
< Content-Type: text/html
<
<html>
<head><title>Hello from Python</title></head>
<body>
<h2>Hello from Python</h2>
</body></html>
* Closing connection 0