chat v3
This commit is contained in:
SDE
2023-08-13 14:50:35 +03:00
parent 2dd03e4d2f
commit 5d806d1498
4 changed files with 39 additions and 24 deletions

View File

@@ -14,10 +14,10 @@ class ChatConsumer(WebsocketConsumer):
print('ws connect') print('ws connect')
self.room_group_name = 'test' self.room_group_name = 'test'
# async_to_sync(self.channel_layer.group_add)( async_to_sync(self.channel_layer.group_add)(
# f'user_{self.scope["user"]["id"]}', f'user_{self.scope["user"].id}',
# self.channel_name self.channel_name
# ) )
print(f'self.room_group_name = {self.room_group_name}') print(f'self.room_group_name = {self.room_group_name}')
print(f'self.channel_name = {self.channel_name}') print(f'self.channel_name = {self.channel_name}')
self.accept() self.accept()
@@ -25,25 +25,34 @@ class ChatConsumer(WebsocketConsumer):
def receive(self, text_data): def receive(self, text_data):
print(f'ws receive text_data = {text_data}') print(f'ws receive text_data = {text_data}')
data = json.loads(text_data)
from .funcs import send_msg from .funcs import send_msg
Dict = send_msg(text_data) Dict = send_msg(text_data)
# print(f'send_msg res = {len(resDict)}')
# self.send(text_data='!!!!')
group_name = f'user_{data["receiver"]}'
resDict = { resDict = {
'type': 'ws_send_msg', 'type': 'echo',
'message': f'group = {group_name}',
# 'sender': resDict['sender']
}
async_to_sync(self.channel_layer.group_send)(
group_name,
resDict
)
resDict = {
'type': 'echo',
'message': Dict, 'message': Dict,
# 'sender': resDict['sender'] # 'sender': resDict['sender']
} }
print(f'send_msg res = {len(resDict)}') group_name = f'user_{data["sender"]}'
# self.send(text_data='!!!!')
async_to_sync(self.channel_layer.group_send)( async_to_sync(self.channel_layer.group_send)(
self.room_group_name, group_name,
resDict resDict
# {
# 'type': 'chat_message',
# 'message': message,
# 'sender': sender
# }
) )
def ws_send_msg(self, data): def ws_send_msg(self, data):

View File

@@ -22,7 +22,7 @@ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TWB.settings')
application = ProtocolTypeRouter({ application = ProtocolTypeRouter({
'http': get_asgi_application(), 'http': get_asgi_application(),
"websocket": AuthMiddlewareStack( "websocket": QueryAuthMiddleware(
URLRouter( URLRouter(
websocket_urlpatterns websocket_urlpatterns
) )

View File

@@ -93,11 +93,11 @@ ASGI_APPLICATION = 'TWB.asgi.application'
CHANNEL_LAYERS = { CHANNEL_LAYERS = {
'default': { 'default': {
# 'BACKEND': 'channels.layers.InMemoryChannelLayer' 'BACKEND': 'channels.layers.InMemoryChannelLayer'
"BACKEND": "channels_redis.core.RedisChannelLayer", # "BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": { # "CONFIG": {
"hosts": [("127.0.0.1", 6379)], # "hosts": [("127.0.0.1", 6379)],
}, # },
} }
} }

View File

@@ -1,10 +1,15 @@
import json
from channels.db import database_sync_to_async from channels.db import database_sync_to_async
@database_sync_to_async @database_sync_to_async
def get_user(user_id): def get_user(data):
from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.models import User, AnonymousUser
try: try:
return User.objects.get(id=user_id) data = data.decode("utf-8")
param_list = data.split('&')
param_Dict = {item.split('=')[0]: item.split('=')[1] for item in param_list}
return User.objects.get(id=param_Dict['user_id'])
except User.DoesNotExist: except User.DoesNotExist:
return AnonymousUser() return AnonymousUser()
@@ -21,6 +26,7 @@ class QueryAuthMiddleware:
# Look up user from query string (you should also do things like # Look up user from query string (you should also do things like
# checking if it is a valid user ID, or if scope["user"] is already # checking if it is a valid user ID, or if scope["user"] is already
# populated). # populated).
scope['user'] = await get_user(int(scope["query_string"])) data = scope['query_string']
scope['user'] = await get_user(data)
return await self.app(scope, receive, send) return await self.app(scope, receive, send)