我也使用memcache來緩存實體,我認爲加快數據庫操作是個好主意。 我選擇將get_key方法添加到類模型,因爲memcache/datastore代理可以在許多類中重用。
定義一個通用的memcache DB代理
#mydb.py
def get_cache(keys):
""" not support async operation
because Async operation conflict with cache logiclly
"""
if not isinstance(keys, list) and not isinstance(keys, tuple):
keys = [keys]
keys = [str(k) for k in keys]
results = memcache.get_multi(keys) #@UndefinedVariable
keys_not_in_cache = [k for k in keys if k not in results]
if keys_not_in_cache:
values = db.get([db.Key(k) for k in keys_not_in_cache])
results_from_db = dict(zip(keys_not_in_cache, values))
results.update(results_from_db)
memcache.set_multi(results_from_db) #@UndefinedVariable
return [results[k] for k in keys]
def put_cache(values):
""" Not support async operation
"""
if not isinstance(values, list):
values = [values]
db.put(values)
keys_str = [(str(k.key()), k) for k in values]
memcache.set_multi(dict(keys_str)) #@UndefinedVariable
def delete_cache(values):
""" Not Support Async Operation
"""
if not isinstance(values, list):
values = [values]
db.delete(values)
keys_str = [str(k.key()) for k in values]
memcache.delete_multi(keys_str) #@UndefinedVariable
用法示例
# for the class want to use this feature
class User(db.Model):
email = db.EmailProperty()
@classmethod
def get_key(cls, email):
return db.Key.from_path(cls.__name__, email)
# Using memcache db proxy
user_keys = [User.get_key(USER_EMAIL_ADDRESS) for USER_EMAIL_ADDRESS in ALL_USER_EMAIL_ADDRESS]
users = mydb.get_cache(user_keys)
「Override」not「overwrite」 – kindall
cls .__ super __。get_by_key_name'正確拼寫super(Entity,cls).get_by_key_name'。 –
好評傢伙,儘管這很快。 –