O'Reilly logo

Using Google App Engine by Charles Severance

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Number Guessing Using the webapp Framework

We can once again revisit our number-guessing game and implement the game as a webapp. Following is the source code for the completed program index.py:

import wsgiref.handlers
from google.appengine.ext import webapp

class MainHandler(webapp.RequestHandler):

  formstring = '''<form method="post" action="/">
<p>Enter Guess: <input type="text" name="guess"/></p>
<p><input type="submit"></p>
</form>'''

  def get(self):
    self.response.out.write('<p>Good luck!</p>\n')
    self.response.out.write(self.formstring)

  def post(self):
    stguess = self.request.get('guess')
    try:
      guess = int(stguess)
    except:
      guess = -1

    answer = 42
    if guess == answer:
      msg = 'Congratulations'
    elif guess < 0 :
      msg = 'Please provide a number guess'
    elif guess < answer:
      msg = 'Your guess is too low'
    else:
      msg = 'Your guess is too high'

    self.response.out.write('<p>Guess:'+stguess+'</p>\n')
    self.response.out.write('<p>'+msg+'</p>\n')
    self.response.out.write(self.formstring)

def main():
  application = webapp.WSGIApplication([
     ('/.*', MainHandler)],
     debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()

If you compare this program to the previous program, you’ll see that the “plumbing” code is identical. We set up the framework and route all incoming URLs to MainHandler. All our changes that make this application different from the previous application are contained in the MainHandler class:

class MainHandler(webapp.RequestHandler): formstring = '''<form ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required