Ejemplos de Memcache

En esta página, se proporcionan ejemplos de código de Python para usar Memcache. Memcache es un sistema de almacenamiento de objetos en la memoria caché distribuida de alto rendimiento que brinda un acceso rápido a los datos almacenados en caché. Para obtener más información sobre Memcache, consulta Descripción general de Memcache.

El patrón de Memcache

Por lo general, Memcache se usa con el patrón siguiente:

  • La aplicación recibe una consulta por parte del usuario o la aplicación.
  • La aplicación verifica si los datos necesarios para responder esa consulta están en Memcache.
    • Si los datos están en Memcache, la aplicación usa esos datos.
    • Si los datos no están en Memcache, la aplicación consulta el almacén de datos y almacena los resultados en Memcache para solicitudes futuras.

El siguiente pseudocódigo representa una solicitud típica de Memcache:

def get_data():
    data = memcache.get('key')
    if data is not None:
        return data
    else:
        data = query_for_data()
        memcache.add('key', data, 60)
    return data

ndb usa Memcache internamente para acelerar las consultas. Sin embargo, también puedes agregar de manera explícita las llamadas a Memcache para obtener un control mayor sobre los aumentos de velocidad.

Cómo almacenar datos en caché

En el siguiente ejemplo, se muestran varias maneras de establecer valores en Memcache mediante la API de Python.

# 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")

A fin de obtener más información sobre los métodos add(), set_multi() y set(), consulta la documentación de la API de Python para Memcache.

Modifica guestbook.py para que use Memcache

El libro de visitas de la guía de introducción consulta el almacén de datos sobre cada solicitud (a través de ndb, por lo que obtiene el aumento de velocidad de Memcache). Puedes modificar la aplicación del libro de visitas para usar Memcache de manera explícita antes de consultar el almacén de datos.

Primero, importaremos el módulo de Memcache y crearemos el método que verificará Memcache antes de ejecutar una consulta.

def get_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))
    if greetings is None:
        greetings = self.render_greetings(guestbook_name)
        try:
            added = memcache.add(
                '{}:greetings'.format(guestbook_name), greetings, 10)
            if not added:
                logging.error('Memcache set failed.')
        except ValueError:
            logging.error('Memcache set failed - data larger than 1MB')
    return greetings

A continuación, separaremos las consultas y la creación del HTML para la página. Cuando no se produzca un acierto de caché, llamaremos a este método para consultar el almacén de datos y compilar la string HTML que almacenaremos en Memcache.

def render_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()
    for greeting in greetings:
        if greeting.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)))
    return output.getvalue()

Por último, actualizaremos el controlador MainPage para llamar al método get_greetings() y obtener algunas estadísticas sobre la cantidad de veces que se produjeron aciertos o errores de caché.


import cgi
import cStringIO
import logging
import urllib

from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import ndb

import webapp2

class Greeting(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)

def guestbook_key(guestbook_name=None):
    """Constructs a Datastore key for a Guestbook entity with guestbook_name"""
    return ndb.Key('Guestbook', guestbook_name or 'default_guestbook')

class MainPage(webapp2.RequestHandler):
    def get(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)))

    def get_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))
        if greetings is None:
            greetings = self.render_greetings(guestbook_name)
            try:
                added = memcache.add(
                    '{}:greetings'.format(guestbook_name), greetings, 10)
                if not added:
                    logging.error('Memcache set failed.')
            except ValueError:
                logging.error('Memcache set failed - data larger than 1MB')
        return greetings

    def render_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()
        for greeting in greetings:
            if greeting.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)))
        return output.getvalue()

class Guestbook(webapp2.RequestHandler):
    def post(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))

        if users.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)