如何使用 cgi 包从 python 发送响应代码

Sha*_*rad 2 html python apache cgi http

我正在使用 cgi 包在 python 中编写脚本。我需要 根据我的代码中的一些检查发送HTTP/1.1 200 OK\nHTTP/1.1 404 Not Found\n的响应。如果我将上述行之一打印为响应的第一行,我的 apache 服务器会记录错误并返回 500 Internal server error 在这种情况下记录的错误消息的相关部分是来自脚本“helo.py”的格式错误的 标头:Bad标头:HTTP/1.1 200 OK\n 谁能指导我我在这里做错了什么。

小智 6

你只打印这些行吗?根据CGI 规范,您必须定义Content-Type.

print "Content-Type: text/html\r\n\r\n";
Run Code Online (Sandbox Code Playgroud)

如果您想发出状态,请改用Status标头(这是 CGI,而不是 HTTP 标头)。

所以

print "Status: 404 Not Found\r\n"
print "Content-Type: text/html\r\n\r\n"
Run Code Online (Sandbox Code Playgroud)

这将解决问题。