20

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

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

cfischer
  • 24,452
  • 37
  • 131
  • 214

2 Answers2

22
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.

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.

bobince
  • 528,062
  • 107
  • 651
  • 834
0

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

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • I don't see why it shouldn't. – SilentGhost Sep 11 '09 at 16:25
  • Only if you're using CGIHTTPServer, though. – bobince Sep 11 '09 at 16:31
  • Foreign as it may seem in this modern age of wrapper libraries and OO frameworks, CGI applications really _do_ just `print` the literal HTTP header error message followed by two newlines to standard output. One can import [`http.HTTPStatus`](https://docs.python.org/3.8/library/http.html#http.HTTPStatus) (introduced in 3.5) if one wants to avoid hard-coding the header, or refer to https://httpstatus.es. – TheDudeAbides Aug 26 '20 at 10:11