Channel Layer Interface Server Worker Server Process 1 ASGI ASGI Asynchronous socket handling Synchronous Django project Interface Server Worker Server ASGI ASGI Worker Server ASGI Process 2 Process 3 Process 4
Channel Layer Worker Server Interface Server Channel Layer Worker Server Interface Server Channel Layer Worker Server Interface Server Channel Layer Worker 1 Worker 2 Worker 3 Redis
Liveblog People open a WebSocket when they open the page Their WebSocket is added to a group When the BlogPost model is saved, we send the post to that group
Their WebSocket is added to a group When the BlogPost model is saved, we send the post to that group def ws_connect(message): Group("liveblog").add(message.reply_channel) class BlogPost(models.Model): ... def save(self, *args, **kwargs): ... Group("liveblog").send({ "text": json.dumps({"id": self.id}), })
When people connect they join a chat group def ws_connect(message): Group("chat").add(message.reply_channel) When we receive a message we send it to the group def ws_receive(message): Group("chat").send({ "text": message["text"], })
...and we tell Django what consumers are joined to which actions. # in routing.py routing = [ route("websocket.connect", consumers.ws_connect), route("websocket.receive", consumers.ws_receive), ] ...and we tell Django what consumers are joined to which actions.
Important notes Runserver just works with WebSockets now Generic Consumers exist Fully worked versions of these two are at github.com/andrewgodwin/channels-examples Django sessions + auth work with WebSockets
FIFO queue with send and receive_many operations, named with a string. Channel Group Named set of channels with add/remove/send operations Cross-process Messages Representations for HTTP and WebSocket sessions
Channel Layer Interface Server Worker Server Process 1 ASGI ASGI Asynchronous socket handling Synchronous Django project Interface Server Worker Server ASGI ASGI Worker Server ASGI Process 2 Process 3 Process 4
Channel Layer Worker Server Interface Server Channel Layer Worker Server Interface Server WSGI App WSGI Server Channel Layer Worker 1 Worker 2 Worker 3 Redis