# Add a value if it doesn't exist in the cache# with a cache expiration of 1 hour.memcache.add(key="weather_USA_98105",value="raining",time=3600)# Set several values, overwriting any existing values for these keys.memcache.set_multi({"USA_98115":"cloudy","USA_94105":"foggy","USA_94043":"sunny"},key_prefix="weather_",time=3600)# Atomically increment an integer value.memcache.set(key="counter",value=0)memcache.incr("counter")memcache.incr("counter")memcache.incr("counter")
defget_greetings(self,guestbook_name):""" get_greetings() Checks the cache to see if there are cached greetings. If not, call render_greetings and set the cache Args: guestbook_name: Guestbook entity group key (string). Returns: A string of HTML containing greetings. """greetings=memcache.get('{}:greetings'.format(guestbook_name))ifgreetingsisNone:greetings=self.render_greetings(guestbook_name)try:added=memcache.add('{}:greetings'.format(guestbook_name),greetings,10)ifnotadded:logging.error('Memcache set failed.')exceptValueError:logging.error('Memcache set failed - data larger than 1MB')returngreetings
接下来,我们将分开页面 HTML 的查询和创建过程。如果缓存未命中,我们将调用此方法来查询数据存储区并构建将在 Memcache 中存储的 HTML 字符串。
defrender_greetings(self,guestbook_name):""" render_greetings() Queries the database for greetings, iterate through the results and create the HTML. Args: guestbook_name: Guestbook entity group key (string). Returns: A string of HTML containing greetings """greetings=ndb.gql('SELECT * ''FROM Greeting ''WHERE ANCESTOR IS :1 ''ORDER BY date DESC LIMIT 10',guestbook_key(guestbook_name))output=cStringIO.StringIO()forgreetingingreetings:ifgreeting.author:output.write('<b>{}</b> wrote:'.format(greeting.author))else:output.write('An anonymous person wrote:')output.write('<blockquote>{}</blockquote>'.format(cgi.escape(greeting.content)))returnoutput.getvalue()
importcgiimportcStringIOimportloggingimporturllibfromgoogle.appengine.apiimportmemcachefromgoogle.appengine.apiimportusersfromgoogle.appengine.extimportndbimportwebapp2classGreeting(ndb.Model):"""Models an individual Guestbook entry with author, content, and date."""author=ndb.StringProperty()content=ndb.StringProperty()date=ndb.DateTimeProperty(auto_now_add=True)defguestbook_key(guestbook_name=None):"""Constructs a Datastore key for a Guestbook entity with guestbook_name"""returnndb.Key('Guestbook',guestbook_nameor'default_guestbook')classMainPage(webapp2.RequestHandler):defget(self):self.response.out.write('<html><body>')guestbook_name=self.request.get('guestbook_name')greetings=self.get_greetings(guestbook_name)stats=memcache.get_stats()self.response.write('<b>Cache Hits:{}</b><br>'.format(stats['hits']))self.response.write('<b>Cache Misses:{}</b><br><br>'.format(stats['misses']))self.response.write(greetings)self.response.write(""" <form action="/sign?{}" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Sign Guestbook"></div> </form> <hr> <form>Guestbook name: <input value="{}" name="guestbook_name">
<input type="submit" value="switch"></form> </body> </html>""".format(urllib.urlencode({'guestbook_name':guestbook_name}),cgi.escape(guestbook_name)))defget_greetings(self,guestbook_name):""" get_greetings() Checks the cache to see if there are cached greetings. If not, call render_greetings and set the cache Args: guestbook_name: Guestbook entity group key (string). Returns: A string of HTML containing greetings. """greetings=memcache.get('{}:greetings'.format(guestbook_name))ifgreetingsisNone:greetings=self.render_greetings(guestbook_name)try:added=memcache.add('{}:greetings'.format(guestbook_name),greetings,10)ifnotadded:logging.error('Memcache set failed.')exceptValueError:logging.error('Memcache set failed - data larger than 1MB')returngreetingsdefrender_greetings(self,guestbook_name):""" render_greetings() Queries the database for greetings, iterate through the results and create the HTML. Args: guestbook_name: Guestbook entity group key (string). Returns: A string of HTML containing greetings """greetings=ndb.gql('SELECT * ''FROM Greeting ''WHERE ANCESTOR IS :1 ''ORDER BY date DESC LIMIT 10',guestbook_key(guestbook_name))output=cStringIO.StringIO()forgreetingingreetings:ifgreeting.author:output.write('<b>{}</b> wrote:'.format(greeting.author))else:output.write('An anonymous person wrote:')output.write('<blockquote>{}</blockquote>'.format(cgi.escape(greeting.content)))returnoutput.getvalue()classGuestbook(webapp2.RequestHandler):defpost(self):# We set the same parent key on the 'Greeting' to ensure each greeting# is in the same entity group. Queries across the single entity group# are strongly consistent. However, the write rate to a single entity# group is limited to ~1/second.guestbook_name=self.request.get('guestbook_name')greeting=Greeting(parent=guestbook_key(guestbook_name))ifusers.get_current_user():greeting.author=users.get_current_user().nickname()greeting.content=self.request.get('content')greeting.put()memcache.delete('{}:greetings'.format(guestbook_name))self.redirect('/?'+urllib.urlencode({'guestbook_name':guestbook_name}))app=webapp2.WSGIApplication([('/',MainPage),('/sign',Guestbook)],debug=True)
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-03-06。"],[[["This document provides Python code examples for utilizing memcache, a high-performance, distributed memory object caching system for fast data access."],["Memcache follows a pattern where the application first checks if the needed data is in the cache, and if not, it queries the Datastore and stores the results in memcache for future use."],["You can set values in memcache using `add()`, `set_multi()`, and `set()` methods, including options for cache expiration and atomic increments of integer values."],["The document explains how to integrate explicit memcache usage into the Guestbook application, which initially relies solely on the Datastore, to improve performance."],["The guestbook application example shows a `get_greetings()` method that queries memcache for cached greetings before querying the Datastore and displays cache statistics."]]],[]]