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

生产环境部署Django Channels遇错:ProtocolTypeRouter缺send参数

解决Django Channels生产环境部署的TypeError问题

错误核心原因

报错TypeError: ProtocolTypeRouter.__call__() missing 1 required positional argument: 'send'的本质:

  • Gunicorn默认使用WSGI工作进程,而ProtocolTypeRouter是ASGI规范的应用接口,WSGI仅传递2个参数,ASGI需要3个参数(scope、receive、send),二者不兼容
  • 配置文件存在两处错误:settings.py中CHANNEL_LAYERS的hosts格式错误,asgi.py缺少get_asgi_application()的导入

具体修复步骤

1. 更换ASGI兼容的启动方式

Gunicorn无法直接运行ASGI应用,任选一种方式即可:

方式一:使用Daphne启动(官方推荐)

替换原Gunicorn命令:

daphne --bind 0.0.0.0:8000 project_name.asgi:application

方式二:Gunicorn搭配Uvicorn ASGI Worker

先安装Uvicorn:

pip install uvicorn

再用以下命令启动:

gunicorn project_name.asgi:application --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

2. 修正配置文件错误

修复settings.py中的CHANNEL_LAYERS

原配置的hosts括号不匹配,且端口应为数字类型:

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],  # 修正括号格式,端口改为数字
        },
    },
}

修复asgi.py的导入缺失

添加get_asgi_application()的导入语句:

import os
from django.core.asgi import get_asgi_application  # 新增导入

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings')
django.setup()

from channels.security.websocket import AllowedHostsOriginValidator
from channels.routing import ProtocolTypeRouter, URLRouter
from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack

import notifications.routing

application = ProtocolTypeRouter({
  'http': get_asgi_application(),
  'websocket': AllowedHostsOriginValidator(
      JWTAuthMiddlewareStack(
          URLRouter(
            notifications.routing.websocket_urlpatterns
          ),
      )
  )
})

3. 生产环境额外检查

  • 确认Redis服务已启动并监听6379端口,执行redis-cli ping验证连通性
  • 检查django_channels_jwt_auth_middleware版本是否与Channels 4.0.0兼容,若出现认证相关错误,可替换为Channels官方的AuthMiddlewareStack

内容的提问来源于stack exchange,提问作者Darren-Jaen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:15:35