Skip to content

Commit 5a03f82

Browse files
committed
barebones websocket consumer
1 parent 07240ea commit 5a03f82

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

dj_idom/asgi.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,27 @@
99

1010
import os
1111

12+
from django.conf.urls import url
1213
from django.core.asgi import get_asgi_application
1314

14-
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_idom.settings')
15+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj_idom.settings")
1516

16-
application = get_asgi_application()
17+
# Fetch ASGI application before importing dependencies that require ORM models.
18+
http_asgi_app = get_asgi_application()
19+
20+
from channels.auth import AuthMiddlewareStack
21+
from channels.routing import ProtocolTypeRouter, URLRouter
22+
from channels.security.websocket import AllowedHostsOriginValidator
23+
24+
from .consumers import CommandConsumer
25+
26+
application = ProtocolTypeRouter(
27+
{
28+
# ASGI app has concurrency problems, see
29+
# See https://github.com/django/channels/issues/1587
30+
"http": http_asgi_app,
31+
"websocket": AllowedHostsOriginValidator(
32+
AuthMiddlewareStack(URLRouter([url("", CommandConsumer().as_asgi())]))
33+
),
34+
}
35+
)

dj_idom/consumers.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""Anything used to construct a websocket endpoint"""
2+
from channels.generic.websocket import AsyncJsonWebsocketConsumer
3+
4+
5+
class CommandConsumer(AsyncJsonWebsocketConsumer):
6+
"""Websocket communication."""
7+
8+
# INITIAL CONNECTION
9+
async def connect(self):
10+
"""When the browser attempts to connect to the server."""
11+
# Accept the connection
12+
await self.accept()
13+
pass
14+
15+
# RECEIVING COMMANDS
16+
async def receive_json(self, content, **kwargs):
17+
"""When the browser attempts to send a message to the server."""
18+
pass

0 commit comments

Comments
 (0)