3

Is it possible to figure the dirty factors of an entity in a pre_put_hook?

I want to conditionally execute some callbacks based on what is being put. E.g. if an entity has a particular property changed, I want to send a mail notification. I can do that manually before calling put() but if the method fails then the put() doesn't get called either.

mehulkar
  • 4,895
  • 5
  • 35
  • 55

3 Answers3

2

Following Brian M. Hunt suggestion, I check the dirty factors using the following code. In this case, I check a property called status:

class Blog(ndb.Model):
  status = ndb.IntegerProperty(default=0)

  def __init__(self, *args, **kwargs):
    # make sure the __old_status__ exists when you `new' an object
    # instead of getting it from DataStore. e.g. b = Blog(status=1)
    super(Blog, self).__init__(*args, **kwargs)
    self.__old_status__ = self.status # I check the status only

  @classmethod
  def _post_get_hook(cls, key, future):
    obj = future.get_result()
    setattr(obj, '__old_status__', obj.status)

  def _pre_put_hook(self):
    if (not self.key.id() or self.__old_status__ != self.status)  and (self.status == 1):
      # the blog is (either a new blog or an existing blog) AND its status is changed to published (e.g. value = 1)
      # do sth e.g. save the time when it is published, update FB object cache and etc.
      pass
Community
  • 1
  • 1
Edward Fung
  • 426
  • 8
  • 16
  • Thanks for the answer. I haven't touched this project in years and unfortunately have no way to verify that this answer is correct (without relearning all of how NDB works), so I can't mark it as accepted. Upvoting as a thank you though until some good netizen comes along and verifies that this a good answer! – mehulkar Nov 30 '15 at 19:23
  • I have verified that this solution works and is an acceptable answer. – SmittySmee Oct 19 '17 at 14:32
1

Sorry, this is not an NDB feature.

Guido van Rossum
  • 16,690
  • 3
  • 46
  • 49
1

You could do this by defining on your ndb.Model a _post_get_hook and a _pre_put_hook that respectively save the original value of the property and compare the value being put to the original.

Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343