使用Celery 5.1.2时报AttributeError: object has no attribute 'task_id'如何解决
错误原因
- 你代码中调用的属性名错误:Celery任务实例存储任务ID的属性为
id而非task_id - 通过
app.current_task全局获取当前任务的方式容易出现上下文偏移问题,稳定性较差
修复方案
推荐使用绑定任务实例的方式获取任务ID,兼容性和稳定性更强,修改后代码如下:
# 装饰器新增 bind=True 参数 @app.task(bind=True, ignore_result=True, name='pydolphin.dolphin.tasks.tasks') # 函数新增第一个参数 self,用于接收Celery自动注入的当前任务实例 def pull_channel_impl(self, channel_id, level): # 通过request对象获取任务ID print(self.request.id) rss = RssSource() source = rss.select_channel_by_id(channel_id) RssPullImpl.single_rss_hub(source, rss, level)
如果不想修改函数参数结构,也可以直接修正属性名完成修复:
print(app.current_task.id)
内容的提问来源于stack exchange,提问作者Dolphin
相关产品推荐
相关产品推荐

