-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Feature/django channels chat app #2228
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Chiemezuo
wants to merge
7
commits into
django-commons:main
Choose a base branch
from
Chiemezuo:feature/django-channels-chat-app
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5877c46
Added async chat app structure
Chiemezuo b7c0883
implement Django channels chat server
Chiemezuo c28970c
Rewrite chat server as asynchronous
Chiemezuo 34e22ac
Added changes to changelog
Chiemezuo dfcc68a
Merge branch 'main' into feature/django-channels-chat-app
Chiemezuo e945d92
Separate concerns in example app
Chiemezuo f07247a
Merge branch 'main' into feature/django-channels-chat-app
Chiemezuo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| # This is the consumer logic for the Django Channels "Web Socket" chat app | ||
Chiemezuo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # https://channels.readthedocs.io/en/latest/tutorial/index.html | ||
| import json | ||
|
|
||
| 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 = f"chat_{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})) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| # This is the routing logic for the Django Channels "Web Socket" chat app | ||
Chiemezuo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # https://channels.readthedocs.io/en/latest/tutorial/index.html | ||
| from django.urls import re_path | ||
|
|
||
| from . import consumers | ||
|
|
||
| websocket_urlpatterns = [ | ||
| re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()), | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,18 @@ | ||
| from django.contrib.auth.models import User | ||
| from django.http import JsonResponse | ||
| from django.shortcuts import render | ||
|
|
||
|
|
||
| async def async_db_view(request): | ||
| names = [] | ||
| async for user in User.objects.all(): | ||
| names.append(user.username) | ||
| return JsonResponse({"names": names}) | ||
|
|
||
|
|
||
| def async_chat_index(request): | ||
| return render(request, "chat/index.html") | ||
|
|
||
|
|
||
| def async_chat_room(request, room_name): | ||
| return render(request, "chat/room.html", {"room_name": room_name}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| {% comment %} | ||
| This template is from the Django Channels "Web Socket" chat app | ||
| https://channels.readthedocs.io/en/latest/tutorial/index.html | ||
| {% endcomment %} | ||
|
|
||
| <!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="UTF-8"> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
| <title>Chat Rooms</title> | ||
| </head> | ||
| <body> | ||
| What chat room would you like to enter?<br> | ||
| <input type="text" id="room-name-input" size="100"><br> | ||
| <input type="button" id="room-name-submit" value="Enter"> | ||
|
|
||
| <script> | ||
| document.querySelector('#room-name-input').focus(); | ||
| document.querySelector('#room-name-input').onkeyup = function(e) { | ||
| if (e.key === 'Enter') { // enter, return | ||
| document.querySelector('#room-name-submit').click() | ||
| } | ||
| } | ||
| document.querySelector('#room-name-submit').onclick = function(e) { | ||
| var roomName = document.querySelector('#room-name-input').value; | ||
| window.location.pathname = 'async/chat/' + roomName + '/'; | ||
| } | ||
| </script> | ||
| </body> | ||
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| {% comment %} | ||
| This template is from the Django Channels "Web Socket" chat app | ||
| https://channels.readthedocs.io/en/latest/tutorial/index.html | ||
| {% endcomment %} | ||
|
|
||
| <!DOCTYPE html> | ||
| <html> | ||
| <head> | ||
| <meta charset="utf-8"> | ||
| <title>Chat Room</title> | ||
| </head> | ||
| <body> | ||
| <textarea id="chat-log" cols="100" rows="20"></textarea><br> | ||
| <input type="text" id="chat-message-input" size="100"><br> | ||
| <input type="button" id="chat-message-submit" value="Send"> | ||
| {{ room_name|json_script:"room-name" }} | ||
| <script> | ||
| const roomName = JSON.parse(document.getElementById('room-name').textContent); | ||
|
|
||
| const chatSocket = new WebSocket( | ||
| 'ws://' | ||
| + window.location.host | ||
| + '/ws/chat/' | ||
| + roomName | ||
| + '/' | ||
| ); | ||
|
|
||
| chatSocket.onmessage = function(e) { | ||
| const data = JSON.parse(e.data); | ||
| document.querySelector('#chat-log').value += (data.message + '\n'); | ||
| }; | ||
|
|
||
| chatSocket.onclose = function(e) { | ||
| console.error('Chat socket closed unexpectedly'); | ||
| } | ||
| document.querySelector('#chat-message-input').focus(); | ||
| document.querySelector('#chat-message-input').onkeyup = function(e) { | ||
| if (e.key === 'Enter') { // enter, return | ||
| document.querySelector('#chat-message-submit').click() | ||
| } | ||
| }; | ||
|
|
||
| document.querySelector('#chat-message-submit').onclick = function(e) { | ||
| const messageInputDom = document.querySelector('#chat-message-input'); | ||
| const message = messageInputDom.value; | ||
| chatSocket.send(JSON.stringify({ | ||
| 'message': message | ||
| })); | ||
| messageInputDom.value = ''; | ||
| } | ||
| </script> | ||
| </body> | ||
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is why the toolbar doesn't work with the channels' consumers. When you send a chat message via the websocket, that message isn't visible in the toolbar anywhere. Only the HTTP requests are. It bypasses the middleware that the toolbar works with.
To start, we would need to define a another middleware that is a subclass of
channels.middleware.BaseMiddleware. There may be other issues that arise after that. However, I think this is enough for us to declare the toolbar doesn't support Django Channels' consumers yet 😢