|
| 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 | +# [START all] |
| 16 | +import os |
| 17 | + |
| 18 | +from google.appengine.api import taskqueue |
| 19 | +from google.appengine.ext import ndb |
| 20 | +import jinja2 |
| 21 | +import webapp2 |
| 22 | + |
| 23 | + |
| 24 | +JINJA_ENV = jinja2.Environment( |
| 25 | + loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) |
| 26 | + |
| 27 | + |
| 28 | +class Counter(ndb.Model): |
| 29 | + count = ndb.IntegerProperty(indexed=False) |
| 30 | + |
| 31 | + |
| 32 | +class CounterHandler(webapp2.RequestHandler): |
| 33 | + def get(self): |
| 34 | + template_values = {'counters': Counter.query()} |
| 35 | + counter_template = JINJA_ENV.get_template('counter.html') |
| 36 | + self.response.out.write(counter_template.render(template_values)) |
| 37 | + |
| 38 | + def post(self): |
| 39 | + key = self.request.get('key') |
| 40 | + if key != '': |
| 41 | + # Add the task to the default queue. |
| 42 | + taskqueue.add(url='/worker', params={'key': key}) |
| 43 | + self.redirect('/') |
| 44 | + |
| 45 | + |
| 46 | +class CounterWorker(webapp2.RequestHandler): |
| 47 | + def post(self): # should run at most 1/s due to entity group limit |
| 48 | + key = self.request.get('key') |
| 49 | + |
| 50 | + @ndb.transactional |
| 51 | + def update_counter(): |
| 52 | + counter = Counter.get_or_insert(key, count=0) |
| 53 | + counter.count += 1 |
| 54 | + counter.put() |
| 55 | + update_counter() |
| 56 | + |
| 57 | + |
| 58 | +app = webapp2.WSGIApplication([ |
| 59 | + ('/', CounterHandler), |
| 60 | + ('/worker', CounterWorker) |
| 61 | +], debug=True) |
| 62 | +# [END all] |
0 commit comments