|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2016 Google Inc. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +import logging |
| 18 | + |
| 19 | +from google.appengine.api import memcache |
| 20 | +import webapp2 |
| 21 | + |
| 22 | + |
| 23 | +def read_from_persistent_store(): |
| 24 | + """Fake method for demonstration purposes. Usually would return |
| 25 | + a value from a database like Cloud Datastore or MySQL.""" |
| 26 | + return "a persistent value" |
| 27 | + |
| 28 | + |
| 29 | +class ReadPage(webapp2.RequestHandler): |
| 30 | + def get(self): |
| 31 | + key = "some-key" |
| 32 | + # [START memcache-read] |
| 33 | + v = memcache.get(key) |
| 34 | + if v is None: |
| 35 | + v = read_from_persistent_store() |
| 36 | + memcache.add(key, v) |
| 37 | + # [END memcache-read] |
| 38 | + |
| 39 | + self.response.content_type = 'text/html' |
| 40 | + self.response.write(str(v)) |
| 41 | + |
| 42 | + |
| 43 | +class DeletePage(webapp2.RequestHandler): |
| 44 | + def get(self): |
| 45 | + key = "some key" |
| 46 | + seconds = 5 |
| 47 | + memcache.set(key, "some value") |
| 48 | + # [START memcache-delete] |
| 49 | + memcache.delete(key, seconds) # clears cache |
| 50 | + # write to persistent datastore |
| 51 | + # Do not attempt to put new value in cache, first reader will do that |
| 52 | + # [END memcache-delete] |
| 53 | + self.response.content_type = 'text/html' |
| 54 | + self.response.write('done') |
| 55 | + |
| 56 | + |
| 57 | +class MainPage(webapp2.RequestHandler): |
| 58 | + def get(self): |
| 59 | + value = 3 |
| 60 | + # [START memcache-failure] |
| 61 | + if not memcache.set('counter', value): |
| 62 | + logging.error("Memcache set failed") |
| 63 | + # Other error handling here |
| 64 | + # [END memcache-failure] |
| 65 | + self.response.content_type = 'text/html' |
| 66 | + self.response.write('done') |
| 67 | + |
| 68 | + |
| 69 | +app = webapp2.WSGIApplication([ |
| 70 | + ('/', MainPage), |
| 71 | + ('/delete', DeletePage), |
| 72 | + ('/read', ReadPage), |
| 73 | +], debug=True) |
0 commit comments