You need to enable JavaScript to run this app. 使用Celery 5.1.2时报AttributeError: object has no attribute 'task_id'如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 19:45:03