Memcache Examples

This page provides code examples in Python code for using Memcache. Memcache is a high-performance, distributed memory object caching system that provides fast access to cached data. To learn more about memcache, read the Memcache Overview.

The memcache Pattern

Memcache is typically used with the following pattern:

  • The application receives a query from the user or the application.
  • The application checks whether the data needed to satisfy that query is in memcache.
    • If the data is in memcache, the application uses that data.
    • If the data is not in memcache, the application queries the datastore and stores the results in memcache for future requests.

The pseudocode below represents a typical memcache request:

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 internally uses memcache to speed up queries. However, if you wish, you can also explicitly add memcache calls to gain more control about the speed-ups.

Caching data

The following example demonstrates several ways to set values in memcache using the Python API.

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

To learn more about the add(), set_multi(), and set() methods, see the memcache Python API documentation.