Override save, put, get, etc… methods in Google App Engine

后端 未结 3 837
情歌与酒
情歌与酒 2020-12-14 12:59

Is it possible to override methids for db.Model in Google App Engine? I want to declare beforeSave, afterSave methods, etc.. to create automatic tagging system.

I kn

3条回答
  •  感情败类
    2020-12-14 13:30

    I've attempted to improve upon the answer by @jbochi:

    1. According to https://developers.google.com/appengine/docs/python/datastore/modelclass#Model_put , put() should return a Key, so the return value from the library should be passed through.
    2. db.Model.save(), while deprecated, is (a) sometimes still used, (b) meant to be a synonym for put() and (c) apparently not called directly by put() - so should be handled manually.

    Revised code:

    class HookedModel(db.Model):
      def before_put(self):
        pass
    
      def after_put(self):
        pass
    
      def put(self, **kwargs):
        self.before_put()
        result = super(HookedModel, self).put(**kwargs)
        self.after_put()
        return result
    
      def save(self, **kwargs):
        self.before_put()
        result = super(HookedModel, self).save(**kwargs)
        self.after_put()
        return result
    

    You should still read http://blog.notdot.net/2010/04/Pre--and-post--put-hooks-for-Datastore-models if you wish to use the monkeypatching, or Chris Farmiloe's answer for use of the async methods.

提交回复
热议问题