tags:

views:

49

answers:

2

Is it possible to use Python as CGI without using the CGI module and still get access to all of the browser information and everything?

I tried:

#!/usr/bin/python
import sys
print "Content-type: text/html"
print
data = sys.stdin.readlines()
print len(data)

but it always prints 0.

+3  A: 

It is indeed possible, but a lot of the information is passed in as environment variables, not on standard input. In fact, the only thing that is passed in on standard input is the body of the incoming request, which would only have contents if a form is being POSTed.

For more information on how to work with CGI, check a website such as http://www.w3.org/CGI/. (It's too much to explain the entire standard in an answer here)

David Zaslavsky
Unfortunately hoohoo.ncsa, the previous standard home of the CGI 1.1 spec linked here, recently went down. The same information in less readable format is available in [RFC 3875](http://www.ietf.org/rfc/rfc3875)
bobince
+1  A: 

Sure. cgi is a utility module with no magic powers; it does nothing you can't do yourself by reading and processing environment variables (in particular QUERY_STRING) and stdin, which comes into play for POST form bodies. (But remember to read the CONTENT_LENGTH environment variable and only read that many bytes, rather than using readlines(), else you can make your script hang waiting for more input that will never come.)

Indeed, there are complete alternatives to cgi for form submission processing, either as standalone modules or as part of a framework.

cgi module or no, however, I wouldn't write a purely CGI-based webapp today. Much better to write to the WSGI interface, and use wsgiref.handlers.CGIHandler to deploy that WSGI app over CGI. Then you can easily migrate to a more efficient web server interface as and when you need to. You can use the cgi module inside a WSGI app to read form submissions if you like, or, again, do your own thing.

bobince