How to Start working with WebSocket in Django

abstract business code coder
Reading Time: 3 minutes

In this blog, we’ll learn about what is WebSocket with its working in Django. So, let’s get started.

What is Web-Socket?

WebSocket is a bi-directional, full-duplex protocol this is used in the same as client-server communication, unlike HTTPS. The WebSocket starts from ws:// or wss://(it is the URL syntax of the WebSocket). It is a stateful protocol that means the connections between client and server will keep alive until It is terminated by either party (client and server). After closing the connection by either client or server, the connection is terminated at both ends.

Start working with WebSocket in Django

Requirements are python 3.5 or above version and Django 2.0.7 or above.
Let’s get started:

Django is support creating WebSocket connections in the form of Django Channels.

Django Channels: It wraps Django’s native asynchronous view support, allowing Django projects to handle not only HTTP but also protocols that require long-running connections, such as WebSockets.

First, create a project in Django and then an application by any name of your choice, using these commands.

django-admin startproject <projectname>
python3 manage.py startapp <applicationname>

Then install Django channels as:

pip install channels(provide version)

Go to your settings.py file and add channels to your list of installed applications and add your application name inside the installed applications

INSTALLED_APPS = [
    'channels', # after the istallation 
    'chatapplication', # my applicaton name
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

after the above process run this command to migrate the database and run the Django server:

python3 manage.py migrate
python3 manage.py runserver

Django by default runs on the WSGI server which doesn’t have support for multi-tasking or asynchronous operations. so we can create a new file asgi.py inside your project. And inside this asgi.py files provide your asynchronous operations.

import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application # for the asgi application
from django.urls import path   # provide the url path 
from chatapp.consumers import * # it is used for the applications views

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket.settings')

application = get_asgi_application()

ws_patterns= [
        
    path('ws/chatapplication/',TestConsumers.as_asgi())
]

application= ProtocolTypeRouter({

    'websocket' : URLRouter(ws_patterns)


})

creating the asgi.py file you can provide asgi to the setting.py file. and install the channels layer.

ASGI_APPLICATION = 'websocket.asgi.application' # websocket my application name

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}

and create a new file inside your application consumers.py (Consumers are the counterpart to Django views.)

after the above process, you can provide the URLs to connect the server inside the Django project

and all the above parts are done, you can use the websocketking to check whether the WebSocket connection is successful or not. using this URL.

ws://localhost:8000/

Difference between WebSocket and HTTP Connection:

WebSocket:

bi-directional protocol.

It is a client-server connection.

almost all real-time applications use this service.

It is faster than the HTTP connection.

HTTP Connection:

uni-directional protocol

Restful applications use the HTTP service.

Slower than the WebSocket connection.

References:

https://websockets.readthedocs.io/en/stable/howto/django.html

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading