Django项目使用channels实现websocket时,
项目文件:mysite/asgi.py
import os
import django
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from socketServer import routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": URLRouter(routing.websocket_urlpatters),
})
项目文件:mysite/setting.py
ASGI_APPLICATION = 'mysite.asgi.application'
启动报错:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/jianyijianse/work/wf/python/djangoApp/djServer/canda/myenv/lib/python3.9/threading.py", line 980, in _bootstrap_inner
self.run()
File "/Users/jianyijianse/work/wf/python/djangoApp/djServer/canda/myenv/lib/python3.9/threading.py", line 917, in run
self._target(*self._args, **self._kwargs)
File "/Users/jianyijianse/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/Users/jianyijianse/.local/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 101, in inner_run
application=self.get_application(options),
File "/Users/jianyijianse/.local/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 126, in get_application
return StaticFilesWrapper(get_default_application())
File "/Users/jianyijianse/.local/lib/python3.9/site-packages/channels/routing.py", line 31, in get_default_application
raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'mysite.asgi'```
**原因:**
channels版本问题,原版本Django4.2, channels2.0.4
解决:
改为:channels4.1.0