EasilyBaffled
EasilyBaffled

Reputation: 3882

HTML in Google App Engine

I have been following this example from google's site, an I am having some trouble understanding some of how the underlying things work. Mostly, When you submit text, in the MainHandler HTML, how does it know to use GuestBook? I assume it has something to do with the <form action="/sign" method=post> and ('/sign', GuestBook) but I'm not entirely sure how it all works.

from google.appengine.ext import db
import webapp2

class Greeting(db.Model):
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello world!')
        self.response.write('<h1>My GuestBook</h1><ol>')
        #greetings = db.GqlQuery("SELECT * FROM Greeting")
        greetings = Greeting.all()
        for greeting in greetings:
            self.response.write('<li> %s' % greeting.content)
        self.response.write('''
            </ol><hr>
            <form action="/sign" method=post>
            <textarea name=content rows=3 cols=60></textarea>
            <br><input type=submit value="Sign Guestbook">
            </form>
        ''')

class GuestBook(webapp2.RequestHandler):
    def post(self):
        greeting = Greeting()
        greeting.content = self.request.get('content')
        greeting.put()
        self.redirect('/')

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/sign', GuestBook),
], debug=True)

Upvotes: 3

Views: 121

Answers (1)

Andbdrew
Andbdrew

Reputation: 11905

You are correct! The routes are configured in the following block:

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/sign', GuestBook),
], debug=True)

So when there is a request to /sign, a new GuestBook instance is created, and the appropriate method is called with the GuestBook instance (which contains a reference to the request) as the first argument. In your example, it is a POST, but webapp2 supports all of the popular http methods as documented at http://webapp-improved.appspot.com/guide/handlers.html

Upvotes: 2

Related Questions