首先下载redis,windows上要下5.0以上的版本,链接为:Releases · tporadowski/redis (github.com)
紧接着python要安装redis,channls以及daphne,asgi_redis
然后在settings中配置
必须放在第一行,以及channles
WSGI_APPLICATION = "start_up_file_km.wsgi.application"
ASGI_APPLICATION = "start_up_file_km.asgi.application"
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
配置ASGI
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "LimsApp.settings.settings")
django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AuthMiddlewareStack(
URLRouter(
socket_urlpatterns
)
),
})
路由配置
from utils import consumers
# 这个变量是存放websocket的路由
socket_urlpatterns = [
path('socket/all/', consumers.ChatConsumer.as_asgi()),
]
websocket代码
import json标签:group,room,启动,asgi,self,django,websocket,message,name From: https://www.cnblogs.com/shangxin-bai/p/18311848
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data):
message = dict(json.loads(text_data))
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))