Python CGI 返回一个 http 状态代码,例如 403?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1411867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:11:02  来源:igfitidea点击:

Python CGI returning an http status code, such as 403?

pythonhttpcgihttp-status-codes

提问by cfischer

How can my python cgi return a specific http status code, such as 403 or 418?

我的 python cgi 如何返回特定的 http 状态代码,例如 403 或 418?

I tried the obvious (print "Status:403 Forbidden") but it doesn't work.

我尝试了显而易见的(打印“Status:403 Forbidden”)但它不起作用。

回答by bobince

print 'Status: 403 Forbidden'
print

Works for me. You do need the second print though, as you need a double-newline to end the HTTP response headers. Otherwise your web server may complain you aren't sending it a complete set of headers.

对我来说有效。不过,您确实需要第二次打印,因为您需要一个双换行符来结束 HTTP 响应标头。否则,您的 Web 服务器可能会抱怨您没有向它发送一组完整的标头。

sys.stdout('Status: 403 Forbidden\r\n\r\n')

may be technically more correct, according to RFC (assuming that your CGI script isn't running in text mode on Windows). However both line endings seem to work everywhere.

根据 RFC(假设您的 CGI 脚本不在 Windows 上以文本模式运行),技术上可能更正确。然而,两个行尾似乎都适用于任何地方。

回答by SilentGhost

I guess, you're looking for send_error. It would be located in http.serverin py3k.

我猜,你正在寻找send_error. 它将位于http.serverpy3k 中。