Posts Tagged ‘forms’

Google App Engine: Basic Form Handling

May 9, 2008

Behind every good psuedo-random generator there is a good seed value for that psuedo-random generator.

The previous three versions of the online randomish generator simply used pythons default seed of the system time. This would be a good place to add a simple HTML form to allow users to enter their own seed value. First off you’ll need to remember to:

import cgi

Then define a class for the seed form input page. Note the standard workhorse HTML form in the code. The action is set equal to “/4” and the method is a post. This class is defined in webapp.WSGIApplication as (‘/4s’, version4Seed) and is the url linked to from the / or entry url for 1boldlentil.

class version4Seed(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write('<form action="/4" method="post">')
    self.response.out.write('<div>Seed value:')
    self.response.out.write('<input type="text" name="theSeed" size="11"></div>')
    self.response.out.write('<div><input type="submit"')
    self.response.out.write('value="Compute Randomish Numbers"></div>')

Then define the page that takes this form post and generates the corresponding random numbers using the seed values. The user seed is passed to the page using cgi.escape(self.request.get(‘theSeed’)) and this value is used to seed the random number generator. Now every time you use the page with the same random number generator the program will return the same 25 numbers.

class version4Page(webapp.RequestHandler):
  def post(self):
    userSeed = int(cgi.escape(self.request.get('theSeed')))
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write('<a href= ')
    self.response.out.write('<b>Randomish Numbers</b></a><p>')
    stop = 25
    i = 1
    while i <= stop:
      i = i + 1

In the main() the webapp.WSGIApplication declares that (‘/4’, version4Page).

Which is pretty easy. Import cgi, define class/url tuple for the form and another class/url tuple to handle the data. Pretty straightforward. And testing on the local machine calling the url /4 directly without filling out the form just returns a blank page. Once its uploaded to appspot though it will give a 405 to try to access the page/url directly without filing in the form.

Version 4 of randomish numbers is here.