[Tutor] reading POST method in cgi script

Eric Abrahamsen eric at abrahamsen.com
Tue Oct 16 05:28:05 CEST 2007


I'm trying to learn the fundamentals of cgi scripting, before moving  
on to actually using the cgi module and, eventually, mod_python. I've  
grasped that, if users submit a form to my cgi script, I can read the  
form contents from os.environ['QUERY_STRING'] if it was stuck in the  
URL via method=get, and from sys.stdin if it was sent via method=post.

The get method works fine, but when it comes to post I can't actually  
read anything off sys.stdin. What's particularly odd is that in my  
test script below, the returnform() function should only be called if  
len(sys.stdin.read())!=0, and yet when I submit a word and the script  
runs returnform(), it tells me that len(sys.stdin.read()) is equal to  
0. If that's the case, how did returnform() get called in the first  
place? Why didn't it just re-run printform()?

At first I tried printing each line of sys.stdin to the HTML page, so  
I could see the details of how post works. Nothing was printed, and  
that's when I tried using len() to see whether sys.stdin contained  
anything. Then, thinking that stdin was getting reset somehow, I  
tried calling returnform() and directly passing in stdin as a  
parameter. That had the same result. Now, I'm thoroughly confused...

Any help would be much appreciated.

Yours,
Eric

************

#!/Library/Frameworks/Python.framework/Versions/Current/bin/python
import sys
import cgitb;cgitb.enable()

def main():
     if len(sys.stdin.read())!=0:
         returnform()
     else:
         printform()

def printform():
     print "Content-Type: text/html\n\n"
     print """
     <html>
     <head></head>
     <body>
     <p>Send us a word.</p>
     <form action="form.py" method="POST" accept-charset="utf-8">

     <p><input type="text" name="theword"></p>

     <p><input type="submit" value="Submit"></p>
     </form>
     </body>
     </html>"""

def returnform():
     print "Content-Type: text/html\n\n"
     print """
     <html>
     <head></head>
     <body>
     <p>Here's what results for standard in:</p>"""
     print "<p>Length of stdin is %s</p>" % len(sys.stdin.read())
     print """
     </body>
     </html>"""

main()


More information about the Tutor mailing list