Created
May 22, 2011 21:33
-
-
Save chrisfarms/985919 to your computer and use it in GitHub Desktop.
async safe before and after save hooks for AppEngine db.Model
This file contains 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
class HookedModel(db.Model): | |
def before_put(self): | |
logging.error("before put") | |
def after_put(self): | |
logging.error("after put") | |
def before_delete(self): | |
logging.error("before delete") | |
def after_delete(self): | |
logging.error("after delete") | |
def put(self): | |
return self.put_async().get_result() | |
def delete(self): | |
return self.delete_async().get_result() | |
def put_async(self): | |
return db.put_async(self) | |
def delete_async(self): | |
return db.delete_async(self) | |
def normalize_entities(entities): | |
if not isinstance(entities, (list, tuple)): | |
entities = (entities,) | |
return [e for e in entities if hasattr(e, 'before_put')] | |
# monkeypatch put_async to call entity.before_put | |
db_put_async = db.put_async | |
def db_put_async_hooked(entities, **kwargs): | |
ents = normalize_entities(entities) | |
for entity in ents: | |
entity.before_put() | |
entity.update_timestamp() | |
a = db_put_async(entities, **kwargs) | |
get_result = a.get_result | |
def get_result_with_callback(): | |
for entity in ents: | |
entity.after_put() | |
return get_result() | |
a.get_result = get_result_with_callback | |
return a | |
db.put_async = db_put_async_hooked | |
# monkeypatch delete_async to call entity.before_delete | |
db_delete_async = db.delete_async | |
def db_delete_async_hooked(entities, **kwargs): | |
ents = normalize_entities(entities) | |
for entity in ents: | |
entity.before_delete() | |
a = db_delete_async(entities, **kwargs) | |
get_result = a.get_result | |
def get_result_with_callback(): | |
for entity in ents: | |
entity.after_delete() | |
return get_result() | |
a.get_result = get_result_with_callback | |
return a | |
db.delete_async = db_delete_async_hooked |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment