forked from GoogleCloudPlatform/appengine-guestbook-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guestbook.py
73 lines (57 loc) · 2.65 KB
/
guestbook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import logging
import os
import jinja2
import webapp2
from google.appengine.api import users
from google.appengine.ext import ndb
from google.appengine.api import memcache
# We set a parent key on the 'Greetings' to ensure that they are all in the same
# entity group. Queries across the single entity group will be consistent.
# However, the write rate should be limited to ~1/second.
def guestbook_key(guestbook_name='default_guestbook'):
return ndb.Key('Guestbook', guestbook_name)
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
class Greeting(ndb.Model):
author = ndb.UserProperty()
content = ndb.StringProperty(indexed=False)
date = ndb.DateTimeProperty(auto_now_add=True)
class MainPage(webapp2.RequestHandler):
def get(self):
guestbook_name = self.request.get('guestbook_name', 'default_guestbook')
greetings = memcache.get('%s:greetings' % guestbook_name)
if not greetings:
greetings_query = Greeting.query(ancestor=guestbook_key(guestbook_name)).order(-Greeting.date)
greetings = greetings_query.fetch(10)
if not memcache.set('%s:greetings' % guestbook_name, greetings):
logging.error('Memcache set failed in GET.')
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(greetings=greetings,
url=url,
url_linktext=url_linktext))
class Guestbook(webapp2.RequestHandler):
def post(self):
guestbook_name = self.request.get('guestbook_name', 'default_guestbook')
greeting = Greeting(parent=guestbook_key(guestbook_name))
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
greetings = memcache.get('%s:greetings' % guestbook_name)
if greetings:
greetings.append(greeting)
if not memcache.set('%s:greetings' % guestbook_name, greetings):
logging.error('Memcache set failed in POST.')
self.redirect('/')
application = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Guestbook),
], debug=True)