Created
December 7, 2009 12:59
-
-
Save Arachnid/250803 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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