RyanovskY
@RyanovskY

Почему не работает вебсокет в джанго?

дерево проекта:
myproject/
├── game/
│   ├── migrations/
│   ├── templates/
│   │       └── game.html
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── consumers.py
│   ├── models.py
│   ├── tests.py
│   └── views.py

├── myproject/
│   ├── static/
│   ├── __init__.py
│   ├── asgi.py
│   ├── routing.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
└── manage.py


#  settings.py
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^vw1x!+s5*05y)8t1d^61'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['46.98.7.168', 'localhost', '127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'channels',
    'game',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'game', 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myproject.wsgi.application'
ASGI_APPLICATION = "myproject.routing.application"


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

LOGIN_URL = '/accounts/login/'
LOGOUT_REDIRECT_URL = '/'

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = 'STATIC_ROOT/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


#  myproject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('game.urls')),
]


#  myproject/routing.py
from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from game import consumers

application = ProtocolTypeRouter({
    "websocket": AuthMiddlewareStack(
        URLRouter([
            path("ws/random_numbers/", consumers.GameConsumer.as_asgi()),
        ])
    ),
})


#  game/consumers.py
import asyncio
import json
import random

from channels.generic.websocket import AsyncWebsocketConsumer


class GameConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

        # Запускаем функцию отправки случайных чисел через 250 миллисекунд
        while True:
            await asyncio.sleep(0.25)  # ждем 0.25 секунды
            random_number = random.randint(1, 100)  # генерируем случайное число от 1 до 100
            await self.send(text_data=json.dumps({
                'number': random_number
            }))

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Обработка полученного сообщения, например, отправка его обратно клиенту
        await self.send(text_data=json.dumps({
            'message': message
        }))


#  game/urls.py

# В файле urls.py вашего приложения

from django.urls import path
from .views import game

urlpatterns = [
    path('', game, name='home'),
]


# game/views.py

from django.shortcuts import render


def game(request):
    return render(request, 'game.html')


<!DOCTYPE html>
<html>
<head>
    <title>Random Number Display</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        const socket = new WebSocket('ws://127.0.0.1:8000/ws/random_numbers/');

        socket.onopen = function() {
            console.log('WebSocket connected');
        };

        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            const number = data.number;
            document.getElementById('random-number').innerHTML = number;
        };

        socket.onclose = function() {
            console.log('WebSocket closed');
        };
    </script>
</head>
<body>
    <h1>Random Number Display</h1>
    <p>Random Number: <span id="random-number"></span></p>
</body>
</html>


asgi.py и wsgi.py по дефолту ничего не менял.

запускаю сервер в разработке:
python manager.py runserver

захожу на страницу и в логах сервера вижу это:
[07/Apr/2024 19:31:49] "GET / HTTP/1.1" 200 786
Not Found: /ws/random_numbers/
[07/Apr/2024 19:31:49] "GET /ws/random_numbers/ HTTP/1.1" 404 2294


почему вебсокет не работает???
  • Вопрос задан
  • 81 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы