如何中止Python脚本并返回404错误?

时间:2017-01-25 13:05:01

标签: python apache http-headers http-status-code-404

我正在编写一个Python脚本来预处理SVG文件。我称之为网址:

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

我想要脚本" includesvg.py"如果404不存在,则返回myfile.svg错误。我尝试过:

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

它没有用。

这一定是一个重复的问题,但有很多问题与#34; Python&#34;和&#34; 404&#34;我无法找到现有答案。

1 个答案:

答案 0 :(得分:0)

您发送的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()

希望这有帮助!