What is the meaning of bind = True keyword in celery?

PythonDjangoCelery

Python Problem Overview


What is the meaning of bind=True in below celery code? When to use it and when not?

@app.task(bind=True)
def send_twitter_status(self, oauth, tweet):
    try:
        twitter = Twitter(oauth)
        twitter.update_status(tweet)
    except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
        raise self.retry(exc=exc)

Python Solutions


Solution 1 - Python

Just a small addition to other answers. As already stated, bound tasks have access to the task instance. One use case when this is needed are retries:

@celery.task(bind=True, max_retries=5)
def retrying(self):
    try:
        return 1/0
    except Exception:
        self.retry(countdown=5)

Another use case is when you want to define custom states for your tasks and be able to set it during task execution:

@celery.task(bind=True)
def show_progress(self, n):
    for i in range(n):
        self.update_state(state='PROGRESS', meta={'current': i, 'total': n})

Solution 2 - Python

Bound tasks

A task being bound means the first argument to the task will always be the task instance (self), just like Python bound methods:

logger = get_task_logger(__name__)

@task(bind=True)
def add(self, x, y):
    logger.info(self.request.id)

Solution 3 - Python

> The bind argument means that the function will be a “bound method” so that you can access attributes and methods on the task type instance.

See the docs

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDevang PadhiyarView Question on Stackoverflow
Solution 1 - PythonTomáš LinhartView Answer on Stackoverflow
Solution 2 - PythonDevang PadhiyarView Answer on Stackoverflow
Solution 3 - PythonYugandhar ChaudhariView Answer on Stackoverflow