|
| 1 | +# Copyright 2016 Google Inc. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an 'AS IS' BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import cgi |
| 16 | + |
| 17 | +from google.appengine.datastore.datastore_query import Cursor |
| 18 | +from google.appengine.ext import ndb |
| 19 | +import webapp2 |
| 20 | + |
| 21 | + |
| 22 | +class Greeting(ndb.Model): |
| 23 | + """Models an individual Guestbook entry with content and date.""" |
| 24 | + content = ndb.StringProperty() |
| 25 | + date = ndb.DateTimeProperty(auto_now_add=True) |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def query_book(cls, ancestor_key): |
| 29 | + return cls.query(ancestor=ancestor_key).order(-cls.date) |
| 30 | + |
| 31 | + |
| 32 | +class MainPage(webapp2.RequestHandler): |
| 33 | + GREETINGS_PER_PAGE = 20 |
| 34 | + |
| 35 | + def get(self): |
| 36 | + guestbook_name = self.request.get('guestbook_name') |
| 37 | + ancestor_key = ndb.Key('Book', guestbook_name or '*notitle*') |
| 38 | + greetings = Greeting.query_book(ancestor_key).fetch( |
| 39 | + self.GREETINGS_PER_PAGE) |
| 40 | + |
| 41 | + self.response.out.write('<html><body>') |
| 42 | + |
| 43 | + for greeting in greetings: |
| 44 | + self.response.out.write( |
| 45 | + '<blockquote>%s</blockquote>' % cgi.escape(greeting.content)) |
| 46 | + |
| 47 | + self.response.out.write('</body></html>') |
| 48 | + |
| 49 | + |
| 50 | +class List(webapp2.RequestHandler): |
| 51 | + GREETINGS_PER_PAGE = 10 |
| 52 | + |
| 53 | + def get(self): |
| 54 | + """Handles requests like /list?cursor=1234567.""" |
| 55 | + cursor = Cursor(urlsafe=self.request.get('cursor')) |
| 56 | + greets, next_cursor, more = Greeting.query().fetch_page( |
| 57 | + self.GREETINGS_PER_PAGE, start_cursor=cursor) |
| 58 | + |
| 59 | + self.response.out.write('<html><body>') |
| 60 | + |
| 61 | + for greeting in greets: |
| 62 | + self.response.out.write( |
| 63 | + '<blockquote>%s</blockquote>' % cgi.escape(greeting.content)) |
| 64 | + |
| 65 | + if more and next_cursor: |
| 66 | + self.response.out.write('<a href="/list?cursor=%s">More...</a>' % |
| 67 | + next_cursor.urlsafe()) |
| 68 | + |
| 69 | + self.response.out.write('</body></html>') |
| 70 | + |
| 71 | + |
| 72 | +app = webapp2.WSGIApplication([ |
| 73 | + ('/', MainPage), |
| 74 | + ('/list', List), |
| 75 | +], debug=True) |
0 commit comments