芹菜中 bind = True 关键字的含义是什么?
What is the meaning of bind = True keyword in celery?
下面celery代码中的bind=True
是什么意思?什么时候用,什么时候不用?
@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)
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.
见docs
绑定任务
一个任务被绑定意味着任务的第一个参数总是任务实例(self),就像Python绑定方法:
logger = get_task_logger(__name__)
@task(bind=True)
def add(self, x, y):
logger.info(self.request.id)
只是对其他答案的一个小补充。如前所述,bound tasks 可以访问任务实例。需要这样做的一个用例是重试:
@celery.task(bind=True, max_retries=5)
def retrying(self):
try:
return 1/0
except Exception:
self.retry(countdown=5)
另一个用例是当您想要为任务定义 custom states 并能够在任务执行期间设置它时:
@celery.task(bind=True)
def show_progress(self, n):
for i in range(n):
self.update_state(state='PROGRESS', meta={'current': i, 'total': n})
下面celery代码中的bind=True
是什么意思?什么时候用,什么时候不用?
@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)
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.
见docs
绑定任务
一个任务被绑定意味着任务的第一个参数总是任务实例(self),就像Python绑定方法:
logger = get_task_logger(__name__)
@task(bind=True)
def add(self, x, y):
logger.info(self.request.id)
只是对其他答案的一个小补充。如前所述,bound tasks 可以访问任务实例。需要这样做的一个用例是重试:
@celery.task(bind=True, max_retries=5)
def retrying(self):
try:
return 1/0
except Exception:
self.retry(countdown=5)
另一个用例是当您想要为任务定义 custom states 并能够在任务执行期间设置它时:
@celery.task(bind=True)
def show_progress(self, n):
for i in range(n):
self.update_state(state='PROGRESS', meta={'current': i, 'total': n})