Tuesday, November 16, 2010

Simple server running Python script on OS X: part 3


Continuing with the project from last time and before (here and here).

I got the form to work. You can use GET as long as there isn't too much data, otherwise, you should use POST. With GET it comes in the QUERY_STRING, as shown last time. The specs are here and some useful info here. It turns out I needed to use the Python library module cgi, and importantly, the text area needed an attribute: name='mytextarea'.

We're coding like it's 1995 :)



script.py

#!/usr/bin/python
import sys, os, cgi

s = '''Content-type: text/html

<head></head>'''

form = cgi.FieldStorage()

print s
print form.keys(),'<br>'
print form.getvalue('sex'),'<br>'
print form.getvalue('vehicle'),'<br>'
data = form.getvalue('mytextarea'),'<br>'
print len(data),'<br>'
print data[0]
print '</body></html>'

form.html

<Content-type: text/html>
<form name="input" action="cgi-bin/script.py" method="post">
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" /><br /><br />
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female<br /><br />
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car<br /><br />
<textarea name='mytextarea' rows="5" cols="40">type here</textarea>
<input type=submit value="Submit" />
</form>
</html>