Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear cache for specific model in NDB

I am in the process of transitioning to the NDB, and I am using two model sets: one based in plain old google.appengine.ext.db and one based on new fancy google.appengine.ext.ndb.

I would like to use NDB-based models for read-only and retain the caching that's built into NDB, while being able to store changes using the old models (and signal the need to update caches to the NDB when needed).

How can I flush/clear cache for a specific model instance in the NDB while saving changes in the model based on old db?

like image 248
Janusz Skonieczny Avatar asked Dec 10 '22 01:12

Janusz Skonieczny


1 Answers

I would recommend just disabling the cache for those model classes that you have in duplicate; better be safe than sorry. This is easily done by putting

   _use_memcache = False
   _use_cache = False

inside each ndb.Model subclass (i.e. before or after the property declarations). Docs for this are here: https://developers.google.com/appengine/docs/python/ndb/cache#policy_functions (look for the table towards the end).

If you really want to clear the cache only when you write an entity using a old db.Model subclass, instead of the above you can try the following (assume ent is a db.Model subclass instance):

  ndbkey = ndb.Key.from_old_key(ent.key())
  ndbkey.delete(use_datastore=False)

This deletes the key from memcache and from the context cache but does not delete it from the datastore. When you try to read it back using its NDB key (or even when it comes back as a query result), however, it will appear to be deleted until the current HTTP request handler finishes, and it will not use memcache for about 30 seconds.

like image 189
Guido van Rossum Avatar answered Dec 24 '22 07:12

Guido van Rossum