Django – Simple channels Example

Django is a great python web framework for server side. If we want to communicate with the client it can be done using the request-response model and also using a web socket especially when we want to send push notifications to the client.

This is a very simple example of how to create and communicate using a channel (web socket) it can be used as a starter for any web application with channels need

First step is to create and activate virtual environment

Install django and create a new app

install channels for web sockets support and asgi_redis for using redis-server as a backend

Add the channels and example to the installed apps (in settings.py)

Add the channel configuration at the end of the settings.py file:

It defines the backend as redis server and set the port

install redis server

start the redis server

run migrate and the server

Edit the file urls.py:

Add urls.py file to the folder example

Add a simple view to views.py file:

Add a template folder (below example) and add index.html file:

In the above code we open a web socket on load and connect to the server. We also added 2 buttons to send ‘start’ and ‘stop’ command to the socket and label for data received

Add the file routing.py to chantest directory: (as we declared it in settings.py file)

Add consumer.py file to example directory:

Test your work – click on start to see the generated numbers in the label and click on stop to disable it

You can download the code from github

 

 

Tagged ,

11 thoughts on “Django – Simple channels Example

  1. Thanks Liran B.H

  2. Getting the following error when I do runserver
    CommandError: You have not set ASGI_APPLICATION, which is needed to run the server.

    1. Did you find a solution?

  3. Is it for Channels 1.x? Do you plan to update it for Channels 2?

  4. yOU SHOULD BETTER PROOFREAD YOUR ARTICLES BEFORE YOU PUBLISH, THERE ARE SEMICOLONS IN THE PYTHON CODEBLOCKS 😉

    1. Oops, sorry, caps. The comment section makes everything capital letter, so I couldn’t see how it would end up 🙂

    2. NO PROBLEM WITH SEMICOLONS IN PYTHON
      it is C/C++/Java/C# friendly

  5. i can it work on django1.9
    and python 2.7

    1. is it it work on django1.9
      and python 2.7

  6. Increase Likes, auto liker, Photo Liker, Photo Auto Liker, Autolike International, autolike, Autoliker, Autolike, Autoliker, Auto Liker, ZFN Liker, Auto Like, Status Auto Liker, autoliker, Working Auto Liker, Status Liker, auto like

Leave a Reply

Your email address will not be published.