add chat box
This commit is contained in:
parent
15b0e06a4f
commit
af61e8a8e8
15 changed files with 175 additions and 6 deletions
0
chat_box/__init__.py
Normal file
0
chat_box/__init__.py
Normal file
3
chat_box/admin.py
Normal file
3
chat_box/admin.py
Normal file
|
@ -0,0 +1,3 @@
|
|||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
5
chat_box/apps.py
Normal file
5
chat_box/apps.py
Normal file
|
@ -0,0 +1,5 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class ChatBoxConfig(AppConfig):
|
||||
name = 'chat_box'
|
47
chat_box/consumers.py
Normal file
47
chat_box/consumers.py
Normal file
|
@ -0,0 +1,47 @@
|
|||
import json
|
||||
|
||||
from channels.generic.websocket import AsyncWebsocketConsumer
|
||||
|
||||
|
||||
class ChatConsumer(AsyncWebsocketConsumer):
|
||||
async def connect(self):
|
||||
self.room_name = 'common'
|
||||
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):
|
||||
text_data_json = json.loads(text_data)
|
||||
message = text_data_json['message']
|
||||
|
||||
# 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,
|
||||
}))
|
0
chat_box/migrations/__init__.py
Normal file
0
chat_box/migrations/__init__.py
Normal file
3
chat_box/models.py
Normal file
3
chat_box/models.py
Normal file
|
@ -0,0 +1,3 @@
|
|||
from django.db import models
|
||||
|
||||
# Create your models here.
|
7
chat_box/routing.py
Normal file
7
chat_box/routing.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
from django.urls import re_path
|
||||
|
||||
from . import consumers
|
||||
|
||||
websocket_urlpatterns = [
|
||||
re_path(r'ws/chat/', consumers.ChatConsumer),
|
||||
]
|
3
chat_box/tests.py
Normal file
3
chat_box/tests.py
Normal file
|
@ -0,0 +1,3 @@
|
|||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
8
chat_box/views.py
Normal file
8
chat_box/views.py
Normal file
|
@ -0,0 +1,8 @@
|
|||
from django.shortcuts import render
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
|
||||
def chat(request):
|
||||
return render(request, 'chat/chat.html', {
|
||||
'title': _('Chat Box'),
|
||||
})
|
Loading…
Add table
Add a link
Reference in a new issue