Django Channels: Synchronous: If An API Call Is Synchronous, It Means That Code Execution Will Block (Or Wait) For
Django Channels: Synchronous: If An API Call Is Synchronous, It Means That Code Execution Will Block (Or Wait) For
Channels is a project that takes Django and extends its abilities beyond HTTP - to handle
WebSocket, chat protocols, IoT protocols, and more. It’s built on a Python specification
called ASGI.
ASGI
ASGI is structured as a single, asynchronous callable. It takes scope , which contains details
about the incoming request, send , an awaitable that lets you send events to the client,
and receive , an awaitable which lets you receive events from the client.
This not only allows multiple incoming events and outgoing events for each application, but also
allows for a background coroutine so the application can do other things (such as listening for
events on an external trigger, like a Redis queue).
HTTP connections have a single-request connection scope - that is, your applications will be
instantiated at the start of the request, and destroyed at the end, even if the underlying socket is
still open and serving multiple requests.
Django itself in a synchronous mode but handling connections and sockets asynchronously, and
giving you the choice to write in either style.
What is a Consumer?
A consumer is the basic unit of Channels code. We call it a consumer as it consumes
events, but you can think of it as its own tiny little application. When a request or new
socket comes in, Channels will follow its routing table - we’ll look at that in a bit - find the
right consumer for that incoming connection, and start up a copy of it.
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.username = "Anonymous"
self.accept()
self.send(text_data="[Welcome %s!]" % self.username)
When Django accepts an HTTP request, it consults the root URLconf to lookup a view
function, and then calls the view function to handle the request. Similarly, when
Channels accepts a WebSocket connection, it consults the root routing configuration to
lookup a consumer, and then calls various functions on the consumer to handle events
from the connection.
Enable a channel layer
A channel layer is a kind of communication system. It allows multiple consumer
instances to talk with each other, and with other parts of Django.
A channel is a mailbox where messages can be sent to. Each channel has a name.
Anyone who has the name of a channel can send a message to the channel.
A group is a group of related channels. A group has a name. Anyone who has the name
of a group can add/remove a channel to the group by name and send a message to all
channels in the group. It is not possible to enumerate what channels are in a particular
group.