0
votes

To reduce datastore reading and writing, people suggest using memcache:

Write:

entity.put()
memcache.set(entity.key.id(), entity)

Read:

# id known:
entity = memcache.get(id)
if entity is None:
    entity = Model.get_by_id(id)
    memcache.set(id, entity)

I'd like to implement the above as two functions:

def memPut(entity):
    entity.put()
    memcache.set(entity.key.id(), entity)

def memGet(Model, id):
    entity = memcache.get(id)
    if entity is None:
        entity = Model.get_by_id(id)
        memcache.set(id, entity)

memGet is just hypothetical. My questions: 1) how do I pass the name of the Model to the function as an parameter? 2) If an entity is created without specifying an id, GAE will use an integer as its id. What if there are two entities (of course from different models) having the same id? Would memcache.get(id) work?

2

2 Answers

2
votes

If you want the same functions available for all entity types, one simple option would be to subclass all your models from a parent model, which implements the following class methods:

class ParentClass(db.Model):
    @classmethod
    def memPut(cls, entity):
        entity.put()
        memcache.set(entity.key().id(), entity)

    @classmethod
    def memGet(cls, id):
        entity = memcache.get(id)
        if entity is None:
             entity = cls.get_by_id(id)
             memcache.set(id, entity)
        return entity

Then, in your handler:

 MyModel.memPut(entity)
 entity = MyModel.memGet(id)
2
votes

Why not use ndb.Model instead of db.Model?

https://developers.google.com/appengine/docs/python/ndb/

The NDB API provides persistent storage in a schemaless object datastore. It supports automatic caching, sophisticated queries, and atomic transactions. NDB is well-suited to storing structured data records. It provides an alternative to the App Engine Datastore API. NDB has some features that the Datastore API lacks:

The StructuredProperty class, which allows entities to have nested structure Integrated automatic caching, which typically gives fast (and inexpensive) reads via an in-context cache and Memcache Asynchronous APIs which allow concurrent actions (and "synchronous" APIs if you don't need that)