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

巧了我就是萌 提交于 2019-11-27 13:29:09

问题


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 know there are hooks, but it seems to me a wrong way to solve this issue :)

Thanks!


回答1:


Yes, it's possible to override these methods. Have a look at this blog post by Nick Johnson.The hooked model class looks this:

class HookedModel(db.Model):
  def before_put(self):
    pass

  def after_put(self):
    pass

  def put(self, **kwargs):
    self.before_put()
    super(HookedModel, self).put(**kwargs)
    self.after_put()

Read the blog to see how to handle the db.put() method too.

You might also be interested on "derived properties".




回答2:


I posted an extension to jbochi's HookedModel class so that the before_put and after_put methods are correctly invoked when called from db.put() and the _async family of functions.

See AppEngine PreCall API hooks




回答3:


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.



来源:https://stackoverflow.com/questions/2752601/override-save-put-get-etc-methods-in-google-app-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!