views:

389

answers:

2

Hi,

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.

+1  A: 

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

SilentGhost
I'm using python 2.5. Will that work?
Fernando
I don't see why it shouldn't.
SilentGhost
Only if you're using CGIHTTPServer, though.
bobince
+1  A: 
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