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

Django中ASGI未正常启动:runserver未显示Channels服务器信息

Django Channels 启动未显示ASGI服务器信息问题排查

问题详情

跟着YouTube上Dennis Ivy的《Django Channels & WebSockets Oversimplified》教程,用Python 3.7.0结合Django和WebSockets搭建简单网站。执行python manage.py runserver时,输出为Starting development server at http://127.0.0.1:8000/,但预期应显示Starting ASGI/Channels version 3.0.0 development server at http://127.0.0.1:8000/。

配置文件如下:

settings.py

INSTALLED_APPS = [
    'channels',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'chat',
]


ASGI_APPLICATION = 'myWebsite.asgi.application'

asgi.py

import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter 

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myWebsite.settings')

application = ProtocolTypeRouter({
    'http':get_asgi_application()
})

解决步骤

  1. 验证Channels版本兼容性
    Python 3.7.0适配Channels 3.0.0,但要确保Django版本为3.2及以上(Channels 3.x的要求)。执行pip show channels确认安装版本,若版本不符,重新安装:

    pip uninstall channels
    pip install channels==3.0.0
    
  2. 修正asgi.py加载逻辑
    当前asgi.py的加载顺序可能导致Channels未被优先初始化,调整为:

    import os
    import django
    from channels.routing import ProtocolTypeRouter
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myWebsite.settings')
    django.setup()
    
    from django.core.asgi import get_asgi_application
    
    application = ProtocolTypeRouter({
        "http": get_asgi_application(),
        # 后续添加WebSocket路由时,可在此处补充配置
    })
    
  3. 确认ASGI配置路径正确性
    检查ASGI_APPLICATION = 'myWebsite.asgi.application'中的myWebsite是否和你的项目根目录名称完全一致(注意大小写),确保asgi.py和settings.py在同一目录下。

  4. 重启开发服务器
    关闭当前运行的runserver进程,重新执行python manage.py runserver,此时应该会显示Channels的ASGI服务器启动信息。

如果问题仍存在,可删除项目中的__pycache__文件夹清除缓存后再次尝试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:10:15