How to raise HTTP error / exception from CGI python script?

How to raise HTTP error / exception from CGI python script?

All that is needed is to print the appropriate heading:

print '''Status: 501 Not Implemented Content-type: text/html ''' 

This does not work correctly.

I have a very simple setup, namely IIS7 routing * .py CGI scripts to python25.exe to execute. I do not use WSGI or FastCGI. Using the "normal" CGI modules: cgitb and cgi

+4
source share
3 answers

This seems to be the way to do it. So far you are following the header format correctly.

Here is someone else who asked the same question, more or less.

Returning http status codes in Python CGI

Do you use HTTP specifications when printing a status code? Can you try to print only the status code, not its description?

Maybe like ...

 print '''Status:501 Content-type: text/html ''' 

Or it should be like ...

 print '''HTTP/1.1 501 Not Implemented Content-type: text/html ''' 

Could you check your installation to check?

Return status from CGI:

http://oreilly.com/openbook/cgi/ch03_07.html

I assume that “Status: 501 is not implemented”, as if it were originally, this is the way to go. I do not know why it does not work. Do you print content without a title before printing a status code?

Another source that confirms that you are doing it right (see section 6.3.3.):

http://www.ietf.org/rfc/rfc3875

EDIT 1,2,3: extended answer

+3
source

Start your script with cgitb.enable() then, to output the correct error code while using the exception:

 try: blah blah failed code except: print "Status: 500" cgitb.handler() 
+2
source

Python CGI returns http status code e.g. 403?

One answer suggested:

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

may be technically more correct, according to the RFC (assuming your CGI script does not work in text mode on Windows). However, both ends of the line seem to work everywhere.

But since you are doing this on windows and you are not ending the title with a status bar ...

 sys.stdout('Status: 501 Not Implemented\n') 

I do not understand why using sys.stdout matters, because since print should use stdout.

0
source

All Articles