Using Python as a CGI script without a CGI module?

Is it possible to use Python as CGI without using the CGI module and still be able to access all 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.

+2


a source to share


2 answers


This is actually possible, but most of the information is passed as environment variables rather than standard input. In fact, the only thing that gets passed on standard input is the body of the incoming request, which will only have content if the form is POSTED.



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

+3


a source


Sure. cgi

is a utility module without magical powers; it doesn't do anything that you can't do yourself by reading and processing environment variables (in particular QUERY_STRING

) and stdin

that come into play for form bodies POST

. (But remember to read the environment variable CONTENT_LENGTH

and only read that many bytes, not use readlines()

, otherwise you might make your script hang, waiting for more input, which will never appear.)

Indeed, there are full alternatives cgi

for handling form submission, either as stand-alone modules or as part of a framework.



cgi

or not, however today I would not write a CGI based web application. It is much better to write an interface in WSGI and use wsgiref.handlers.CGIHandler

WSGI over CGI to deploy this application. Then you can easily upgrade to a more efficient web server interface as needed. You can use a module cgi

inside a WSGI application to read forms if you like, or again, do your thing.

+1


a source







All Articles