asgi + daphne

This commit is contained in:
aa.afanasyev 2025-07-15 01:34:22 +09:00
parent 6f4282d96e
commit 9bf24b072b
7 changed files with 76 additions and 31 deletions

View file

@ -8,9 +8,21 @@ https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.core.asgi import get_asgi_application
from .routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testapi.settings')
application = get_asgi_application()
django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})

14
testapi/consumers.py Normal file
View file

@ -0,0 +1,14 @@
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class EchoConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
await self.send(text_data=json.dumps({"message": "WebSocket connected!"}))
async def disconnect(self, close_code):
pass
async def receive(self, text_data):
await self.send(text_data=json.dumps({"echo": text_data}))

8
testapi/routing.py Normal file
View file

@ -0,0 +1,8 @@
# routing.py
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path("ws/echo/", consumers.EchoConsumer.as_asgi()),
]

View file

@ -99,7 +99,7 @@ TEMPLATES = [
]
WSGI_APPLICATION = 'testapi.wsgi.application'
ASGI_APPLICATION = 'testapi.asgi.application'
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases