test for ws

This commit is contained in:
2025-07-15 19:09:45 +08:00
parent 01e5c9097c
commit 4d4ae96022
7 changed files with 93 additions and 2 deletions

View File

@@ -9,8 +9,16 @@ 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 .urls import ws_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings")
application = get_asgi_application()
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(URLRouter(ws_urlpatterns)),
}
)

View File

@@ -47,6 +47,7 @@ INSTALLED_APPS = [
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"channels",
"ninja",
"corsheaders",
"django_extensions",
@@ -86,6 +87,8 @@ TEMPLATES = [
WSGI_APPLICATION = "api.wsgi.application"
ASGI_APPLICATION = "api.asgi.application"
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
@@ -129,6 +132,15 @@ else:
# 配置缓存
CACHES = PROD_CACHES
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [(os.getenv("REDIS_HOST"), 6379)],
},
},
}
# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

View File

@@ -20,6 +20,7 @@ from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from ninja import NinjaAPI
from .ws import Consumer
api = NinjaAPI()
@@ -35,3 +36,7 @@ apis = [
]
urlpatterns = apis + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
ws_urlpatterns = [
path("ws/", Consumer.as_asgi()),
]

11
api/ws.py Normal file
View File

@@ -0,0 +1,11 @@
from channels.generic.websocket import AsyncWebsocketConsumer
class Consumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
async def disconnect(self):
pass
async def receive(self, text_data):
await self.send(text_data=text_data)