Channel Layers In Django – Auriga

Published On: 27 April 2021.By .
  • General

Channels Layers In Django

Channel Layers allow us to create interaction between different instances of an application, mostly used to create real-time applications, we can say it’s an alternative to sockets. Channel Layers are purely async interfaces (for both sender and receiver), you have to wrap them in a wrapper container if you want them to behave synchronously.

Channel Layer configurations

You can configure Channel Layer via CHANNEL_LAYERS in the settings file. you can get the default channel layer in your project with

In case are in consumer you can get it with

Redis Channel Layer – (Channels Layers in Django)

channel_redis is the only official Django-maintained channel layer support for production use. Redis Channel layer uses redis as its backing store. you can configure it by putting the below configurations in your settings file.

Code Example, when Redis is running on localhost (127.0.0.2) and on port (6379

In Memory Channel Layer- (Channels Layers in Django)

we can also use channels with In-memory store by using In-Memory Channel Layer, you can configure it by putting the following piece of code in your settings file.

Implementation of Channel layers with an example

for more understanding with Channel layers in Django let’s discuss and Chat room example.

Let’s create an app for Chat room.

adding creating app to installed_apps in settings file

creating a template as a output view.

put the following code in chat/templates/chat/index.html

now rendering template as view by adding following code in chat/views.py

URL configurations for the above-rendered view by putting the following code in chat/urls.py

Including Chat app URL configurations to main URL configurations

Integrating Channel library

configuring channels by putting the following code in my settings file.

adding chat room template in chat/templates/chat/room.html file

rendering chat room view in chat/views.py

adding URL for chat room in URL file( chat/urls.py)

now we have to create a consumer to control this  whole process as in the chat/consumers.py file

as to configure above consumer with and URL we have to define URL routing in chat/routing.py file

here we go now run command python manage.py runserver  and hit URL  “/chat-room/”,  by doing so you can visit a chat room, if you are opening the same URL in two different tabs, you are able to pass the messages in between two tabs without page load.

 

Related content

That’s all for this blog