Skip to content

Instantly share code, notes, and snippets.

@Arachnid
Created December 7, 2009 12:59
Show Gist options
  • Save Arachnid/250803 to your computer and use it in GitHub Desktop.
Save Arachnid/250803 to your computer and use it in GitHub Desktop.
from google.appengine.ext import db
class EntityCache(object):
"""Caches fetched entities so subsequent fetches return the same instance.
Usage:
cache = EntityCache()
e1, e2 = cache.get([k1, k2])
e3, e4 = cache.get([k2, k3])
assert e2 == e3
"""
def __init__(self):
self.cache = {}
def get(self, keys):
"""Get the entities matching the provided keys."""
if isinstance(keys, db.Key):
keys = [keys]
missing_keys = [k for k in keys if k not in self.cache]
if missing_keys:
self.cache.update((x.key(), x) for x in db.get(missing_keys))
return [self.cache[k] for k in keys]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment