0

I was just wondering what the best practice to pass an attribute to base class task would be in Celery 4.3.

I have already working code which looks like:

class BaseTask(app.Task):
    abc = None

    def __init__(self, *args, **kwargs):
        if not self.abc:
            raise NotImplementedError('Must implement the abc attribute')
        super(BaseTask, self).__init__(*args, **kwargs)

    def on_success(self, retval, task_id, args, kwargs):
        print(asd)  # and do some other work with asd

class MainTask(BaseTask):
    abc = 'Here Am I'
    def run(self, *args, **kwargs):
       print(self.abc)  # and do some other great job


MainTask = app.register_task(MainTask())

But as I can see in Celery documentation:

http://docs.celeryproject.org/en/latest/_modules/celery/app/base.html?highlight=register_task

 Note:
            This is here for compatibility with old Celery 1.0
            style task classes, you should not need to use this for
            new projects.

and at http://docs.celeryproject.org/en/4.0/whatsnew-4.0.html#the-task-base-class-no-longer-automatically-register-tasks

The best practice is to use custom task classes only for overriding general behavior, and then using the task decorator to realize the task

it isn't best practice what I have done.

So is there any better way/best practice to pass an attribute to Base Task?

Krzysieqq
  • 921
  • 7
  • 10
  • Hi, you are not so far of the main idea of the registration of a Task, [check this question](https://stackoverflow.com/a/41794225/5342275) – Patricio Jun 13 '19 at 17:06
  • @Patricio with celery >= 4 is no longer using a special meta-class that automatically registers the task in the task registry. It using: `CustomTask = app.register_task(CustomTask())` http://docs.celeryproject.org/en/4.0/whatsnew-4.0.html#the-task-base-class-no-longer-automatically-register-tasks – Krzysieqq Jun 14 '19 at 12:10
  • `app.register_task` its an interface for retrocompatibility with older versions of the celery, in the new versions you should use `your_app.tasks.register(CustomTask(arg1, args2, ...))` which is the way to register Class based tasks. I can provide an example – Patricio Jun 14 '19 at 13:00

0 Answers0