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

@ -1,3 +1,4 @@
version: '3.8'
services: services:
db: db:
@ -13,6 +14,7 @@ services:
web: web:
build: . build: .
command: daphne -b 0.0.0.0 -p 8000 testapi.asgi:application
ports: ports:
- "8000:8000" - "8000:8000"
volumes: volumes:

View file

@ -1,3 +1,6 @@
events {}
http {
upstream django { upstream django {
server web:8000; server web:8000;
} }
@ -30,5 +33,10 @@ server {
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
} }
} }

View file

@ -7,3 +7,4 @@ requests
django-cors-headers django-cors-headers
Pillow Pillow
python-dotenv python-dotenv
channels>=4.0

View file

@ -8,9 +8,21 @@ https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
""" """
import os import os
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.core.asgi import get_asgi_application from django.core.asgi import get_asgi_application
from .routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testapi.settings') 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' WSGI_APPLICATION = 'testapi.wsgi.application'
ASGI_APPLICATION = 'testapi.asgi.application'
# Database # Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases # https://docs.djangoproject.com/en/5.1/ref/settings/#databases