5

I'm writing alot of tasks that are very similar, and want to know how to better subclass the Task to reduce boilerplate. Since a Task is only instatiated once, I you can't put things in __init__ like I show below, but it should illustrate the point.

what I'm trying to accomplish:

class EmailTaskOne(Task):
    def run(self, object_id):
        email_data = EmailData.objects.get(pk=object_id)
        data = self.do_common_stuff(email_data)
        self.do_unique_stuff(data)

class EmailTaskTwo(Task):
    def run(self, object_id):
        email_data = EmailData.objects.get(pk=object_id)
        data = self.do_common_stuff(email_data)
        self.do_unique_stuff2(data)

# lots more tasks like this

What I would like to have is:

class BaseEmailTask(Task):
     abstract = True
     #...Insert Magic Here...

class EmailTaskOne(BaseEmailTask):
     def run(self, object_id):
         self.do_unique_stuff(self.data)

So, since __init__ is right out, where do I setup the class in the abstract class. I can define a bunch of functions quite easily if all I want to do is factor out some stuff, but some (lots) of the boilerplate depends on the object_id.

yarbelk
  • 7,215
  • 6
  • 29
  • 37
  • possible duplicate of [celery task and customize decorator](http://stackoverflow.com/questions/6393879/celery-task-and-customize-decorator) – Louis Feb 26 '15 at 13:29
  • While the solution is applicable - the question asked is different. As such, I don't think its a duplicate. If I was trying to increase DRYness of my tasks by using mixins and sublcassing of tasks - I would not be looking for 'customize decorator', but 'subclass' or 'mixin' or something like that. – yarbelk Feb 27 '15 at 03:08

1 Answers1

6

Does mine and MauroRocco's answer help you?

see celery task and customize decorator

There I succeeded to pass arguments to an extended Task

Community
  • 1
  • 1
michel.iamit
  • 5,788
  • 9
  • 55
  • 74