views:

97

answers:

1

I'm trying to implement a delayed blog post deletion scheme. So instead of an annoying Are you sure?, you get a 2 minute time frame to cancel deletion.

I want to track What will be deleted When with a db.Model class (DeleteQueueItem), as I found no way to delete a task from the queue and suspect I can query what's there.

Creating a DeleteQueueItem entity should automatically set a delete_when property and add a task to the queue. I use the relative path of blog posts as their key_name and want to use that as key_name here, too. This led me to a custom init:

class DeleteQueueItem(db.Model):
    """Model to keep track of items that will be deleted via task queue."""

    # URL path to the blog post is handled as key_name
    delete_when = db.DateTimeProperty()

    def __init__(self, **kwargs):
    delay = 120  # Seconds
    t = datetime.timedelta(seconds=delay)
    deadline = datetime.datetime.now() - t
    key_name = kwargs.get('key_name')

    db.Model.__init__(self, **kwargs)
    self.delete_when = deadline

    taskqueue.add(url='/admin/task/delete_page', 
                    countdown=delay,
                    params={'path': key_name})

This seems to work, until I try to delete the entity:

fetched_item = models.DeleteQueueItem.get_by_key_name(path)

This fails with:

TypeError: __init__() takes exactly 1 non-keyword argument (2 given)

What am I doing wrong?

+2  A: 

Generally, you shouldn't try and override the init method of Model classes. While it's possible to get right, the correct constructor behaviour is fairly complex, and may even change between releases, breaking your code (though we try to avoid doing so!). Part of the reason for this is that the constructor has to be used both by your own code, to construct new models, and by the framework, to reconstitute models loaded from the datastore.

A better approach is to use a factory method, which you call instead of the constructor.

Also, you probably want to add the task at the same time as you write the entity, rather than at creation time. If you don't, you end up with a race condition: the task may execute before you've stored the new entity to the datastore!

Here's a suggested refactoring:

class DeleteQueueItem(db.Model):
    """Model to keep track of items that will be deleted via task queue."""

    # URL path to the blog post is handled as key_name
    delete_when = db.DateTimeProperty()

    @classmethod
    def new(cls, key_name):
        delay = 120  # Seconds
        t = datetime.timedelta(seconds=delay)
        deadline = datetime.datetime.now() - t

        return cls(key_name=key_name, delete_when=deadline)

    def put(self, **kwargs):
      def _tx():
        taskqueue.add(url='/admin/task/delete_page', 
                      countdown=delay,
                      params={'path': key_name},
                      transactional=True)
        return super(DeleteQueueItem, self).put(**kwargs)
      if not self.is_saved():
        return db.run_in_transaction(_tx)
      else:
        return super(DeleteQueueItem, self).put(**kwargs)
Nick Johnson
Great, thank you!A problem with that, where I have a hard time thinking of an elegant solution, is that delay and key_name are not available in def _tx(), though.
thorwil
Oops, good point. You can define 'delay' as a class member (eg, at the top level), since it appears to be a constant, and the key name can be accessed as self.key().name().
Nick Johnson
Got it to work! delay as class member was clear enough, but I would never have arrived at self.key().name(). Thanks again!
thorwil
Nick, what about setting default values? The doc's recommend creating your own __init__: http://code.google.com/appengine/docs/python/datastore/propertyclass.html#Property
Fraser Harris
I see how Will McCutchen uses super(ModelSubClass, self).__init__. Great way to set generated default values. Maybe expand the doc linked above (see Constructor > class Property > default > Note)?http://stackoverflow.com/questions/2465675/custom-keys-for-google-app-engine-models-python
Fraser Harris