3

我一直在关注谷歌网站上的这个例子,我在理解一些底层事物的工作方式时遇到了一些麻烦。大多数情况下,当您在 MainHandler HTML 中提交文本时,它如何知道使用留言簿?我认为它与<form action="/sign" method=post>and有关,('/sign', GuestBook)但我不完全确定它是如何工作的。

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)
4

1 回答 1

2

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

于 2013-05-21T02:09:15.387 回答