├── .gitignore ├── README.md ├── chat ├── __init__.py ├── admin.py ├── apps.py ├── consumers.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── routing.py ├── static │ ├── index.js │ └── room.js ├── templates │ ├── index.html │ └── room.html ├── tests.py ├── urls.py └── views.py ├── core ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/pycharm+all,python,django 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=pycharm+all,python,django 3 | 4 | ### Django ### 5 | *.log 6 | *.pot 7 | *.pyc 8 | __pycache__/ 9 | local_settings.py 10 | db.sqlite3 11 | db.sqlite3-journal 12 | media 13 | 14 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 15 | # in your Git repository. Update and uncomment the following line accordingly. 16 | # /staticfiles/ 17 | 18 | ### Django.Python Stack ### 19 | # Byte-compiled / optimized / DLL files 20 | *.py[cod] 21 | *$py.class 22 | 23 | # C extensions 24 | *.so 25 | 26 | # Distribution / packaging 27 | .Python 28 | build/ 29 | develop-eggs/ 30 | dist/ 31 | downloads/ 32 | eggs/ 33 | .eggs/ 34 | lib/ 35 | lib64/ 36 | parts/ 37 | sdist/ 38 | var/ 39 | wheels/ 40 | share/python-wheels/ 41 | *.egg-info/ 42 | .installed.cfg 43 | *.egg 44 | MANIFEST 45 | 46 | # PyInstaller 47 | # Usually these files are written by a python script from a template 48 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 49 | *.manifest 50 | *.spec 51 | 52 | # Installer logs 53 | pip-log.txt 54 | pip-delete-this-directory.txt 55 | 56 | # Unit test / coverage reports 57 | htmlcov/ 58 | .tox/ 59 | .nox/ 60 | .coverage 61 | .coverage.* 62 | .cache 63 | nosetests.xml 64 | coverage.xml 65 | *.cover 66 | *.py,cover 67 | .hypothesis/ 68 | .pytest_cache/ 69 | cover/ 70 | 71 | # Translations 72 | *.mo 73 | 74 | # Django stuff: 75 | 76 | # Flask stuff: 77 | instance/ 78 | .webassets-cache 79 | 80 | # Scrapy stuff: 81 | .scrapy 82 | 83 | # Sphinx documentation 84 | docs/_build/ 85 | 86 | # PyBuilder 87 | .pybuilder/ 88 | target/ 89 | 90 | # Jupyter Notebook 91 | .ipynb_checkpoints 92 | 93 | # IPython 94 | profile_default/ 95 | ipython_config.py 96 | 97 | # pyenv 98 | # For a library or package, you might want to ignore these files since the code is 99 | # intended to run in multiple environments; otherwise, check them in: 100 | # .python-version 101 | 102 | # pipenv 103 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 104 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 105 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 106 | # install all needed dependencies. 107 | #Pipfile.lock 108 | 109 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 110 | __pypackages__/ 111 | 112 | # Celery stuff 113 | celerybeat-schedule 114 | celerybeat.pid 115 | 116 | # SageMath parsed files 117 | *.sage.py 118 | 119 | # Environments 120 | .env 121 | .venv 122 | env/ 123 | venv/ 124 | ENV/ 125 | env.bak/ 126 | venv.bak/ 127 | 128 | # Spyder project settings 129 | .spyderproject 130 | .spyproject 131 | 132 | # Rope project settings 133 | .ropeproject 134 | 135 | # mkdocs documentation 136 | /site 137 | 138 | # mypy 139 | .mypy_cache/ 140 | .dmypy.json 141 | dmypy.json 142 | 143 | # Pyre type checker 144 | .pyre/ 145 | 146 | # pytype static type analyzer 147 | .pytype/ 148 | 149 | # Cython debug symbols 150 | cython_debug/ 151 | 152 | ### PyCharm+all ### 153 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 154 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 155 | 156 | # User-specific stuff 157 | .idea/**/workspace.xml 158 | .idea/**/tasks.xml 159 | .idea/**/usage.statistics.xml 160 | .idea/**/dictionaries 161 | .idea/**/shelf 162 | 163 | # AWS User-specific 164 | .idea/**/aws.xml 165 | 166 | # Generated files 167 | .idea/**/contentModel.xml 168 | 169 | # Sensitive or high-churn files 170 | .idea/**/dataSources/ 171 | .idea/**/dataSources.ids 172 | .idea/**/dataSources.local.xml 173 | .idea/**/sqlDataSources.xml 174 | .idea/**/dynamic.xml 175 | .idea/**/uiDesigner.xml 176 | .idea/**/dbnavigator.xml 177 | 178 | # Gradle 179 | .idea/**/gradle.xml 180 | .idea/**/libraries 181 | 182 | # Gradle and Maven with auto-import 183 | # When using Gradle or Maven with auto-import, you should exclude module files, 184 | # since they will be recreated, and may cause churn. Uncomment if using 185 | # auto-import. 186 | # .idea/artifacts 187 | # .idea/compiler.xml 188 | # .idea/jarRepositories.xml 189 | # .idea/modules.xml 190 | # .idea/*.iml 191 | # .idea/modules 192 | # *.iml 193 | # *.ipr 194 | 195 | # CMake 196 | cmake-build-*/ 197 | 198 | # Mongo Explorer plugin 199 | .idea/**/mongoSettings.xml 200 | 201 | # File-based project format 202 | *.iws 203 | 204 | # IntelliJ 205 | out/ 206 | 207 | # mpeltonen/sbt-idea plugin 208 | .idea_modules/ 209 | 210 | # JIRA plugin 211 | atlassian-ide-plugin.xml 212 | 213 | # Cursive Clojure plugin 214 | .idea/replstate.xml 215 | 216 | # Crashlytics plugin (for Android Studio and IntelliJ) 217 | com_crashlytics_export_strings.xml 218 | crashlytics.properties 219 | crashlytics-build.properties 220 | fabric.properties 221 | 222 | # Editor-based Rest Client 223 | .idea/httpRequests 224 | 225 | # Android studio 3.1+ serialized cache file 226 | .idea/caches/build_file_checksums.ser 227 | 228 | ### PyCharm+all Patch ### 229 | # Ignores the whole .idea folder and all .iml files 230 | # See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 231 | 232 | .idea/ 233 | 234 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 235 | 236 | *.iml 237 | modules.xml 238 | .idea/misc.xml 239 | *.ipr 240 | 241 | # Sonarlint plugin 242 | .idea/sonarlint 243 | 244 | # End of https://www.toptal.com/developers/gitignore/api/pycharm+all,python,django 245 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django Channels Tutorial 2 | 3 | ## Want to learn how to build this? 4 | 5 | Check out the [tutorial](https://testdriven.io/blog/django-channels/). 6 | 7 | ## Want to use this project? 8 | 9 | 1. Fork/Clone 10 | 11 | 1. Create and activate a virtual environment: 12 | 13 | ```sh 14 | $ python3 -m venv venv && source venv/bin/activate 15 | ``` 16 | 17 | 1. Install the requirements: 18 | 19 | ```sh 20 | (venv)$ pip install -r requirements.txt 21 | ``` 22 | 23 | 1. Apply the migrations: 24 | 25 | ```sh 26 | (venv)$ python manage.py migrate 27 | ``` 28 | 29 | 1. Start a Redis server for backing storage: 30 | 31 | ```sh 32 | (venv)$ docker run -p 6379:6379 -d redis:5 33 | ``` 34 | 35 | 1. Run the server: 36 | 37 | ```sh 38 | (venv)$ python manage.py runserver 39 | ``` 40 | 41 | 1. By default, only authenticated users can chat. To create a test user: 42 | 43 | ```sh 44 | (venv)$ python manage.py createsuperuser 45 | ``` 46 | 47 | 1. Log in using your newly created user at [http://localhost:8000/admin/](http://localhost:8000/admin/). 48 | 49 | 1. Navigate to [http://localhost:8000/chat/](http://localhost:8000/chat/). 50 | -------------------------------------------------------------------------------- /chat/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/testdrivenio/django-channels-example/86b0a13d3a557fd0d2f95c2c089a2e6e18ca919e/chat/__init__.py -------------------------------------------------------------------------------- /chat/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from chat.models import Room, Message 4 | 5 | admin.site.register(Room) 6 | admin.site.register(Message) 7 | -------------------------------------------------------------------------------- /chat/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ChatConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'chat' 7 | -------------------------------------------------------------------------------- /chat/consumers.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from asgiref.sync import async_to_sync 4 | from channels.generic.websocket import WebsocketConsumer 5 | 6 | from .models import Room, Message 7 | 8 | 9 | class ChatConsumer(WebsocketConsumer): 10 | 11 | def __init__(self, *args, **kwargs): 12 | super().__init__(args, kwargs) 13 | self.room_name = None 14 | self.room_group_name = None 15 | self.room = None 16 | self.user = None 17 | self.user_inbox = None 18 | 19 | def connect(self): 20 | self.room_name = self.scope['url_route']['kwargs']['room_name'] 21 | self.room_group_name = f'chat_{self.room_name}' 22 | self.room = Room.objects.get(name=self.room_name) 23 | self.user = self.scope['user'] 24 | self.user_inbox = f'inbox_{self.user.username}' 25 | 26 | # connection has to be accepted 27 | self.accept() 28 | 29 | # join the room group 30 | async_to_sync(self.channel_layer.group_add)( 31 | self.room_group_name, 32 | self.channel_name, 33 | ) 34 | 35 | # send the user list to the newly joined user 36 | self.send(json.dumps({ 37 | 'type': 'user_list', 38 | 'users': [user.username for user in self.room.online.all()], 39 | })) 40 | 41 | if self.user.is_authenticated: 42 | # create a user inbox for private messages 43 | async_to_sync(self.channel_layer.group_add)( 44 | self.user_inbox, 45 | self.channel_name, 46 | ) 47 | 48 | # send the join event to the room 49 | async_to_sync(self.channel_layer.group_send)( 50 | self.room_group_name, 51 | { 52 | 'type': 'user_join', 53 | 'user': self.user.username, 54 | } 55 | ) 56 | self.room.online.add(self.user) 57 | 58 | def disconnect(self, close_code): 59 | async_to_sync(self.channel_layer.group_discard)( 60 | self.room_group_name, 61 | self.channel_name, 62 | ) 63 | 64 | if self.user.is_authenticated: 65 | # delete the user inbox for private messages 66 | async_to_sync(self.channel_layer.group_discard)( 67 | self.user_inbox, 68 | self.channel_name, 69 | ) 70 | 71 | # send the leave event to the room 72 | async_to_sync(self.channel_layer.group_send)( 73 | self.room_group_name, 74 | { 75 | 'type': 'user_leave', 76 | 'user': self.user.username, 77 | } 78 | ) 79 | self.room.online.remove(self.user) 80 | 81 | def receive(self, text_data=None, bytes_data=None): 82 | text_data_json = json.loads(text_data) 83 | message = text_data_json['message'] 84 | 85 | if not self.user.is_authenticated: 86 | return 87 | if message.startswith('/pm '): 88 | split = message.split(' ', 2) 89 | target = split[1] 90 | target_msg = split[2] 91 | 92 | # send private message to the target 93 | async_to_sync(self.channel_layer.group_send)( 94 | f'inbox_{target}', 95 | { 96 | 'type': 'private_message', 97 | 'user': self.user.username, 98 | 'message': target_msg, 99 | } 100 | ) 101 | # send private message delivered to the user 102 | self.send(json.dumps({ 103 | 'type': 'private_message_delivered', 104 | 'target': target, 105 | 'message': target_msg, 106 | })) 107 | return 108 | 109 | # send chat message event to the room 110 | async_to_sync(self.channel_layer.group_send)( 111 | self.room_group_name, 112 | { 113 | 'type': 'chat_message', 114 | 'user': self.user.username, 115 | 'message': message, 116 | } 117 | ) 118 | Message.objects.create(user=self.user, room=self.room, content=message) 119 | 120 | def chat_message(self, event): 121 | self.send(text_data=json.dumps(event)) 122 | 123 | def user_join(self, event): 124 | self.send(text_data=json.dumps(event)) 125 | 126 | def user_leave(self, event): 127 | self.send(text_data=json.dumps(event)) 128 | 129 | def private_message(self, event): 130 | self.send(text_data=json.dumps(event)) 131 | 132 | def private_message_delivered(self, event): 133 | self.send(text_data=json.dumps(event)) 134 | -------------------------------------------------------------------------------- /chat/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.0 on 2022-01-07 18:16 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.db.models.deletion 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ('auth', '0012_alter_user_first_name_max_length'), 15 | ] 16 | 17 | operations = [ 18 | migrations.CreateModel( 19 | name='Room', 20 | fields=[ 21 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 22 | ('name', models.CharField(max_length=128)), 23 | ('online', models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL)), 24 | ], 25 | ), 26 | migrations.CreateModel( 27 | name='Message', 28 | fields=[ 29 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 30 | ('content', models.CharField(max_length=512)), 31 | ('timestamp', models.DateTimeField(auto_now_add=True)), 32 | ('room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat.room')), 33 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='auth.user')), 34 | ], 35 | ), 36 | ] 37 | -------------------------------------------------------------------------------- /chat/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/testdrivenio/django-channels-example/86b0a13d3a557fd0d2f95c2c089a2e6e18ca919e/chat/migrations/__init__.py -------------------------------------------------------------------------------- /chat/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import User 2 | from django.db import models 3 | 4 | 5 | class Room(models.Model): 6 | name = models.CharField(max_length=128) 7 | online = models.ManyToManyField(to=User, blank=True) 8 | 9 | def get_online_count(self): 10 | return self.online.count() 11 | 12 | def join(self, user): 13 | self.online.add(user) 14 | self.save() 15 | 16 | def leave(self, user): 17 | self.online.remove(user) 18 | self.save() 19 | 20 | def __str__(self): 21 | return f'{self.name} ({self.get_online_count()})' 22 | 23 | 24 | class Message(models.Model): 25 | user = models.ForeignKey(to=User, on_delete=models.CASCADE) 26 | room = models.ForeignKey(to=Room, on_delete=models.CASCADE) 27 | content = models.CharField(max_length=512) 28 | timestamp = models.DateTimeField(auto_now_add=True) 29 | 30 | def __str__(self): 31 | return f'{self.user.username}: {self.content} [{self.timestamp}]' 32 | -------------------------------------------------------------------------------- /chat/routing.py: -------------------------------------------------------------------------------- 1 | from django.urls import re_path 2 | 3 | from . import consumers 4 | 5 | websocket_urlpatterns = [ 6 | re_path(r'ws/chat/(?P\w+)/$', consumers.ChatConsumer.as_asgi()), 7 | ] 8 | -------------------------------------------------------------------------------- /chat/static/index.js: -------------------------------------------------------------------------------- 1 | console.log("Sanity check from index.js."); 2 | 3 | // focus 'roomInput' when user opens the page 4 | document.querySelector("#roomInput").focus(); 5 | 6 | // submit if the user presses the enter key 7 | document.querySelector("#roomInput").onkeyup = function(e) { 8 | if (e.keyCode === 13) { // enter key 9 | document.querySelector("#roomConnect").click(); 10 | } 11 | }; 12 | 13 | // redirect to '/room//' 14 | document.querySelector("#roomConnect").onclick = function() { 15 | let roomName = document.querySelector("#roomInput").value; 16 | window.location.pathname = "chat/" + roomName + "/"; 17 | } 18 | 19 | // redirect to '/room//' 20 | document.querySelector("#roomSelect").onchange = function() { 21 | let roomName = document.querySelector("#roomSelect").value.split(" (")[0]; 22 | window.location.pathname = "chat/" + roomName + "/"; 23 | } 24 | -------------------------------------------------------------------------------- /chat/static/room.js: -------------------------------------------------------------------------------- 1 | console.log("Sanity check from room.js."); 2 | 3 | const roomName = JSON.parse(document.getElementById('roomName').textContent); 4 | 5 | let chatLog = document.querySelector("#chatLog"); 6 | let chatMessageInput = document.querySelector("#chatMessageInput"); 7 | let chatMessageSend = document.querySelector("#chatMessageSend"); 8 | let onlineUsersSelector = document.querySelector("#onlineUsersSelector"); 9 | 10 | // adds a new option to 'onlineUsersSelector' 11 | function onlineUsersSelectorAdd(value) { 12 | if (document.querySelector("option[value='" + value + "']")) return; 13 | let newOption = document.createElement("option"); 14 | newOption.value = value; 15 | newOption.innerHTML = value; 16 | onlineUsersSelector.appendChild(newOption); 17 | } 18 | 19 | // removes an option from 'onlineUsersSelector' 20 | function onlineUsersSelectorRemove(value) { 21 | let oldOption = document.querySelector("option[value='" + value + "']"); 22 | if (oldOption !== null) oldOption.remove(); 23 | } 24 | 25 | // focus 'chatMessageInput' when user opens the page 26 | chatMessageInput.focus(); 27 | 28 | // submit if the user presses the enter key 29 | chatMessageInput.onkeyup = function(e) { 30 | if (e.keyCode === 13) { // enter key 31 | chatMessageSend.click(); 32 | } 33 | }; 34 | 35 | // clear the 'chatMessageInput' and forward the message 36 | chatMessageSend.onclick = function() { 37 | if (chatMessageInput.value.length === 0) return; 38 | chatSocket.send(JSON.stringify({ 39 | "message": chatMessageInput.value, 40 | })); 41 | chatMessageInput.value = ""; 42 | }; 43 | 44 | let chatSocket = null; 45 | 46 | function connect() { 47 | chatSocket = new WebSocket("ws://" + window.location.host + "/ws/chat/" + roomName + "/"); 48 | 49 | chatSocket.onopen = function(e) { 50 | console.log("Successfully connected to the WebSocket."); 51 | } 52 | 53 | chatSocket.onclose = function(e) { 54 | console.log("WebSocket connection closed unexpectedly. Trying to reconnect in 2s..."); 55 | setTimeout(function() { 56 | console.log("Reconnecting..."); 57 | connect(); 58 | }, 2000); 59 | }; 60 | 61 | chatSocket.onmessage = function(e) { 62 | const data = JSON.parse(e.data); 63 | console.log(data); 64 | 65 | switch (data.type) { 66 | case "chat_message": 67 | chatLog.value += data.user + ": " + data.message + "\n"; 68 | break; 69 | case "user_list": 70 | for (let i = 0; i < data.users.length; i++) { 71 | onlineUsersSelectorAdd(data.users[i]); 72 | } 73 | break; 74 | case "user_join": 75 | chatLog.value += data.user + " joined the room.\n"; 76 | onlineUsersSelectorAdd(data.user); 77 | break; 78 | case "user_leave": 79 | chatLog.value += data.user + " left the room.\n"; 80 | onlineUsersSelectorRemove(data.user); 81 | break; 82 | case "private_message": 83 | chatLog.value += "PM from " + data.user + ": " + data.message + "\n"; 84 | break; 85 | case "private_message_delivered": 86 | chatLog.value += "PM to " + data.target + ": " + data.message + "\n"; 87 | break; 88 | default: 89 | console.error("Unknown message type!"); 90 | break; 91 | } 92 | 93 | // scroll 'chatLog' to the bottom 94 | chatLog.scrollTop = chatLog.scrollHeight; 95 | }; 96 | 97 | chatSocket.onerror = function(err) { 98 | console.log("WebSocket encountered an error: " + err.message); 99 | console.log("Closing the socket."); 100 | chatSocket.close(); 101 | } 102 | } 103 | connect(); 104 | 105 | onlineUsersSelector.onchange = function() { 106 | chatMessageInput.value = "/pm " + onlineUsersSelector.value + " "; 107 | onlineUsersSelector.value = null; 108 | chatMessageInput.focus(); 109 | }; 110 | -------------------------------------------------------------------------------- /chat/templates/index.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | django-channels-chat 7 | 8 | 9 | 14 | 15 | 16 |
17 |

django-channels-chat

18 |
19 |
20 |
21 | 22 | 23 | If the room doesn't exist yet, it will be created for you. 24 |
25 | 26 |
27 |
28 | 29 | 34 |
35 |
36 |
37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /chat/templates/room.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | django-channels-chat 7 | 8 | 9 | 20 | 21 | 22 |
23 |

django-channels-chat

24 |
25 |
26 |
27 | 28 | 29 |
30 |
31 | 32 |
33 | 34 |
35 |
36 |
37 |
38 | 39 | 41 |
42 |
43 | {{ room.name|json_script:"roomName" }} 44 |
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /chat/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /chat/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('', views.index_view, name='chat-index'), 7 | path('/', views.room_view, name='chat-room'), 8 | ] 9 | -------------------------------------------------------------------------------- /chat/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | from chat.models import Room 4 | 5 | 6 | def index_view(request): 7 | return render(request, 'index.html', { 8 | 'rooms': Room.objects.all(), 9 | }) 10 | 11 | 12 | def room_view(request, room_name): 13 | chat_room, created = Room.objects.get_or_create(name=room_name) 14 | return render(request, 'room.html', { 15 | 'room': chat_room, 16 | }) 17 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/testdrivenio/django-channels-example/86b0a13d3a557fd0d2f95c2c089a2e6e18ca919e/core/__init__.py -------------------------------------------------------------------------------- /core/asgi.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from channels.auth import AuthMiddlewareStack 4 | from channels.routing import ProtocolTypeRouter, URLRouter 5 | from django.core.asgi import get_asgi_application 6 | 7 | import chat.routing 8 | 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') 10 | 11 | application = ProtocolTypeRouter({ 12 | 'http': get_asgi_application(), 13 | 'websocket': AuthMiddlewareStack( 14 | URLRouter( 15 | chat.routing.websocket_urlpatterns 16 | ) 17 | ), 18 | }) 19 | -------------------------------------------------------------------------------- /core/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for core project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.0. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-94=1j=n6rby0fglmw_%@#_n8oe65+q=flh8hd%lf8!qm%4cjhz' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'chat.apps.ChatConfig', 41 | 'channels', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'core.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'core.wsgi.application' 73 | ASGI_APPLICATION = 'core.asgi.application' 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/4.0/ref/settings/#databases 78 | 79 | DATABASES = { 80 | 'default': { 81 | 'ENGINE': 'django.db.backends.sqlite3', 82 | 'NAME': BASE_DIR / 'db.sqlite3', 83 | } 84 | } 85 | 86 | 87 | # Password validation 88 | # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators 89 | 90 | AUTH_PASSWORD_VALIDATORS = [ 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 99 | }, 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 102 | }, 103 | ] 104 | 105 | 106 | # Internationalization 107 | # https://docs.djangoproject.com/en/4.0/topics/i18n/ 108 | 109 | LANGUAGE_CODE = 'en-us' 110 | 111 | TIME_ZONE = 'UTC' 112 | 113 | USE_I18N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/4.0/howto/static-files/ 120 | 121 | STATIC_URL = 'static/' 122 | 123 | # Default primary key field type 124 | # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field 125 | 126 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 127 | 128 | CHANNEL_LAYERS = { 129 | 'default': { 130 | 'BACKEND': 'channels_redis.core.RedisChannelLayer', 131 | 'CONFIG': { 132 | "hosts": [('127.0.0.1', 6379)], 133 | }, 134 | }, 135 | } 136 | -------------------------------------------------------------------------------- /core/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path, include 3 | 4 | urlpatterns = [ 5 | path('chat/', include('chat.urls')), 6 | path('admin/', admin.site.urls), 7 | ] 8 | -------------------------------------------------------------------------------- /core/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for core project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==4.0 2 | channels==3.0.4 3 | channels-redis==3.3.1 4 | --------------------------------------------------------------------------------