├── .gitignore ├── DjangoWebSocketChat ├── __init__.py ├── asgi.py ├── routing.py ├── settings.py ├── urls.py └── wsgi.py ├── chat ├── __init__.py ├── admin.py ├── apps.py ├── consumers.py ├── migrations │ └── __init__.py ├── models.py ├── routing.py ├── tests.py ├── urls.py └── views.py ├── db.sqlite3 ├── manage.py └── templates └── chat ├── index.html └── room.html /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | venv 3 | local_settings.py 4 | __pycache__/ 5 | */__pycache__/ 6 | *.py[cod] 7 | .pyc 8 | .env 9 | -------------------------------------------------------------------------------- /DjangoWebSocketChat/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DJWOMS/DjangoWebSocketChatBackEnd/0f9a9bc004d3853ff9e5a5db129ba9da617cb23e/DjangoWebSocketChat/__init__.py -------------------------------------------------------------------------------- /DjangoWebSocketChat/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for DjangoWebSocketChat project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebSocketChat.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /DjangoWebSocketChat/routing.py: -------------------------------------------------------------------------------- 1 | from channels.auth import AuthMiddlewareStack 2 | from channels.routing import ProtocolTypeRouter, URLRouter 3 | 4 | import chat.routing 5 | 6 | application = ProtocolTypeRouter({ 7 | 'websocket': AuthMiddlewareStack( 8 | URLRouter(chat.routing.websocket_urlpatterns) 9 | ), 10 | }) 11 | -------------------------------------------------------------------------------- /DjangoWebSocketChat/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for DjangoWebSocketChat project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.0.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '*)ofhy9!q0qh80v$09e2tje&h%ol01o)0n@rh(d&rn73(wke_o' 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 | 41 | 'channels', 42 | 'chat', 43 | ] 44 | 45 | MIDDLEWARE = [ 46 | 'django.middleware.security.SecurityMiddleware', 47 | 'django.contrib.sessions.middleware.SessionMiddleware', 48 | 'django.middleware.common.CommonMiddleware', 49 | 'django.middleware.csrf.CsrfViewMiddleware', 50 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 | 'django.contrib.messages.middleware.MessageMiddleware', 52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53 | ] 54 | 55 | ROOT_URLCONF = 'DjangoWebSocketChat.urls' 56 | 57 | TEMPLATES = [ 58 | { 59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 | 'DIRS': [os.path.join(BASE_DIR, 'templates')] 61 | , 62 | 'APP_DIRS': True, 63 | 'OPTIONS': { 64 | 'context_processors': [ 65 | 'django.template.context_processors.debug', 66 | 'django.template.context_processors.request', 67 | 'django.contrib.auth.context_processors.auth', 68 | 'django.contrib.messages.context_processors.messages', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'DjangoWebSocketChat.wsgi.application' 75 | 76 | 77 | # Database 78 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 79 | 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django.db.backends.sqlite3', 83 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 84 | } 85 | } 86 | 87 | 88 | # Password validation 89 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 90 | 91 | AUTH_PASSWORD_VALIDATORS = [ 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 103 | }, 104 | ] 105 | 106 | 107 | # Internationalization 108 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 109 | 110 | LANGUAGE_CODE = 'en-us' 111 | 112 | TIME_ZONE = 'UTC' 113 | 114 | USE_I18N = True 115 | 116 | USE_L10N = True 117 | 118 | USE_TZ = True 119 | 120 | 121 | # Static files (CSS, JavaScript, Images) 122 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 123 | 124 | STATIC_URL = '/static/' 125 | 126 | 127 | ASGI_APPLICATION = "DjangoWebSocketChat.routing.application" 128 | 129 | CHANNEL_LAYERS = { 130 | 'default': { 131 | 'BACKEND': 'channels_redis.core.RedisChannelLayer', 132 | 'CONFIG': { 133 | "hosts": [('127.0.0.1', 6379)], 134 | }, 135 | }, 136 | } 137 | -------------------------------------------------------------------------------- /DjangoWebSocketChat/urls.py: -------------------------------------------------------------------------------- 1 | """DjangoWebSocketChat URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('', include('chat.urls')), 22 | ] 23 | -------------------------------------------------------------------------------- /DjangoWebSocketChat/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for DjangoWebSocketChat 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/3.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', 'DjangoWebSocketChat.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /chat/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DJWOMS/DjangoWebSocketChatBackEnd/0f9a9bc004d3853ff9e5a5db129ba9da617cb23e/chat/__init__.py -------------------------------------------------------------------------------- /chat/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /chat/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ChatConfig(AppConfig): 5 | name = 'chat' 6 | -------------------------------------------------------------------------------- /chat/consumers.py: -------------------------------------------------------------------------------- 1 | from asgiref.sync import async_to_sync 2 | from channels.generic.websocket import WebsocketConsumer 3 | import json 4 | 5 | 6 | class ChatConsumer(WebsocketConsumer): 7 | def connect(self): 8 | self.room_name = self.scope['url_route']['kwargs']['room_name'] 9 | self.room_group_name = 'chat_%s' % self.room_name 10 | 11 | async_to_sync(self.channel_layer.group_add)( 12 | self.room_group_name, 13 | self.channel_name 14 | ) 15 | 16 | self.accept() 17 | 18 | def disconnect(self, close_code): 19 | async_to_sync(self.channel_layer.group_discard)( 20 | self.room_group_name, 21 | self.channel_name 22 | ) 23 | 24 | def receive(self, text_data): 25 | text_data_json = json.loads(text_data) 26 | message = text_data_json['message'] 27 | username = text_data_json['username'] 28 | 29 | async_to_sync(self.channel_layer.group_send)( 30 | self.room_group_name, 31 | { 32 | 'type': 'chat_message', 33 | 'message': message, 34 | 'username': username 35 | } 36 | ) 37 | 38 | def chat_message(self, event): 39 | message = event['message'] 40 | username = event['username'] 41 | 42 | self.send(text_data=json.dumps({ 43 | 'event': "Send", 44 | 'message': message, 45 | 'username': username 46 | })) 47 | -------------------------------------------------------------------------------- /chat/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DJWOMS/DjangoWebSocketChatBackEnd/0f9a9bc004d3853ff9e5a5db129ba9da617cb23e/chat/migrations/__init__.py -------------------------------------------------------------------------------- /chat/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /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), 7 | ] 8 | -------------------------------------------------------------------------------- /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, name='index'), 7 | path('/', views.room, name='room'), 8 | ] 9 | -------------------------------------------------------------------------------- /chat/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.shortcuts import render 4 | from django.utils.safestring import mark_safe 5 | 6 | 7 | def index(request): 8 | """Главная страница""" 9 | return render(request, 'chat/index.html', {}) 10 | 11 | 12 | def room(request, room_name): 13 | """""" 14 | return render(request, 'chat/room.html', { 15 | 'room_name_json': mark_safe(json.dumps(room_name)) 16 | }) 17 | -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DJWOMS/DjangoWebSocketChatBackEnd/0f9a9bc004d3853ff9e5a5db129ba9da617cb23e/db.sqlite3 -------------------------------------------------------------------------------- /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 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebSocketChat.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /templates/chat/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Chat Rooms 6 | 7 | 8 | What chat room would you like to enter?
9 |
10 | 11 | 12 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /templates/chat/room.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Chat Room 6 | 7 | 8 |
9 |
10 | 11 | 12 | 45 | 46 | --------------------------------------------------------------------------------