You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django集成Celery遇TypeError:get_response()获chat_id多值错误

问题

在Django结合Celery开发时遇到错误:
TypeError: get_response() got multiple values for argument 'chat_id'

调用任务的代码:

i = get_response.delay(chat_id=chat_id, is_first_message=is_first_message, question=question, user_id=user_id)

任务函数定义:

@shared_task(bind=True)
def get_response(chat_id: int, is_first_message: bool,
                     question: str, user_id: int) -> str:
    # 函数逻辑...

已确认chat_id是单个整数,但问题依旧存在,完整报错栈追踪:

[03/Jul/2023 13:52:16] ERROR "django.request" Internal Server Error: /chat/chat/1/283/new_message/
project      | Traceback (most recent call last):
project      |   File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
project      |     response = get_response(request)
project      |                ^^^^^^^^^^^^^^^^^^^^^
project      |   File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
project      |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
project      |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
project      |   File "/code/apps/chat/views.py", line 82, in new_message
project      |     i = get_response.delay(chat_id=chat_id, is_first_message=is_first_message,question=question,user_id=user_id)
project      |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
project      |   File "/usr/local/lib/python3.11/site-packages/celery/app/task.py", line 425, in delay
project      |     return self.apply_async(args, kwargs)
project      |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
project      |   File "/usr/local/lib/python3.11/site-packages/celery/app/task.py", line 540, in apply_async
project      |     check_arguments(*(args or ()), **(kwargs or {}))
project      | TypeError: get_response() got multiple values for argument 'chat_id'
project      | [03/Jul/2023 13:52:16] ERROR "django.server" "POST /chat/chat/1/283/new_message/ HTTP/1.1" 500 87645
解决方法

错误根源在于@shared_task(bind=True)装饰器:当bind=True时,Celery会自动把任务实例本身作为第一个参数传入函数,但你的函数定义里第一个参数是chat_id,导致参数传递冲突——Celery传入的实例会被当作chat_id,而你又通过关键字参数传入了chat_id,于是出现“多个值传入同一个参数”的错误。

有两种修复方案:

  1. 如果不需要使用任务实例(比如不需要访问self.request等属性),直接去掉bind=True:
@shared_task
def get_response(chat_id: int, is_first_message: bool,
                     question: str, user_id: int) -> str:
    # 函数逻辑...
  1. 如果必须保留bind=True,需要把self作为函数的第一个参数:
@shared_task(bind=True)
def get_response(self, chat_id: int, is_first_message: bool,
                     question: str, user_id: int) -> str:
    # 可通过self访问任务相关属性,比如self.request
    # 函数逻辑...

调整后重新调用任务,错误即可解决。

内容的提问来源于stack exchange,提问作者Goomblepop

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:25:23