如何中止 Python 脚本和 return 404 错误?

How to abort a Python script and return a 404 error?

我正在编写 Python 脚本来预处理 SVG 文件。我称 URL 为:

http://example.com/includesvg.py?/myfile.svg

如果 myfile.svg 不存在,我希望脚本“includesvg.py”到 return 一个 404 错误。我试过:

print "Status: 404 Not Found\r\n"
print "Content-Type: text/html\r\n\r\n"
print "<h1>404 File not found!</h1>"

没用。

这一定是一个重复的问题,但是 "Python" 和“404”的问题太多了,我找不到现有的答案。

您发送的 HTTP 响应无效。我会这样做:

print('HTTP/1.1 404 Not Found\r\n')
print('Content-Type: text/html\r\n\r\n')
print('<html><head></head><body><h1>404 Not Found</h1></body></html>')

导致(美化):

HTTP/1.1 404 Not Found
Content-Type: text/html

<html>
  <head>
  </head>
  <body>
    <h1>404 Not Found</h1>
  </body>
</html>

但是,这个也可以:

import sys
sys.stdout('Status: 404 Not Found\r\n\r\n')

作为以下的简化版本:

print('Status: 404 Not Found')
print()

希望对您有所帮助!