django channle的使用
频道在PyPI上可用 - 要安装它,只需运行: 参照:https://channels.readthedocs.io/en/latest/introduction.html
pip install -U channels
安装 channels_redis
pip install channels_redis
安装redis: windows 参照 https://www.cnblogs.com/juncaoit/p/10122642.html
ubuntu 参照以下命令
apt-get install redis-server
完成后,您应该添加channels
到您的 INSTALLED_APPS
设置:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
...
'channels',
)
然后,在以下位置进行默认路由myproject/routing.py
:
# mysite/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import apiService.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( apiService.routing.websocket_urlpatterns ) ), })
最后,将您的ASGI_APPLICATION
设置设置为指向该路由对象作为根应用程序:
ASGI_APPLICATION = "myproject.routing.application"
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
一旦启用本地服务,channels也将在响应的端口启用ws服务 (服务器上则不同)
apiService中的路由:
# chat/routing.py # from django.urls import path from django.conf.urls import url from . import consumers,admin_ws websocket_urlpatterns = [ # path('ws/admin_chat/:admin_id/', admin_ws.AdminWs), # path('ws/cons_chat/:cons_id/', consumers.ChatConsumer), url(r'^ws/admin_chat/(?P<admin_id>[^/]+)/$', admin_ws.AdminWs), url(r'^ws/cons_chat/(?P<cons_id>[^/]+)/$', consumers.ChatConsumer), # url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer), ]
注:服务器上要用:supervisor 和 asgi来部署。为了避免mysql链接失效:
from django.db import close_old_connections # 自己定义一个decorator,用来装饰使用数据库的函数 def close_old_connections_wrapper(func): def wrapper(*args, **kwargs): close_old_connections() return func(*args, **kwargs) return wrapper
可在connect函数中调用 close_old_connections