Day 21 – WebSockets in Python: Real-Time Applications Explained

Introduction

Traditional web applications rely on HTTP requests, where the client must repeatedly ask the server for updates. This request-response model works for many scenarios but is inefficient for real-time applications like chat apps, live notifications, or collaborative platforms.

Enter WebSockets—a protocol that enables full-duplex communication between client and server. This allows instant data transmission, turning Python applications into real-time, interactive experiences.

At CuriosityTech, we emphasize WebSockets as a key skill for modern Full Stack developers, especially for building applications in 2025 where real-time interaction is a user expectation.


HTTP vs WebSockets

FeatureHTTPWebSockets
CommunicationRequest-responseFull-duplex
ConnectionStateless (new request each time)Persistent
LatencyHigher (due to repeated requests)Low (real-time)
Best ForStatic content, CRUD APIsChat, notifications, live dashboards

💡 Analogy: HTTP = Sending letters for every message.
WebSockets = A phone call where you can talk back and forth instantly.


Setting Up WebSockets in Python

Option 1: Using Django Channels

  1. Install Django Channels

pip install channels channels_redis

  1. Update settings.py

INSTALLED_APPS += [‘channels’]

ASGI_APPLICATION = ‘myproject.asgi.application’

# Redis configuration for channel layers

CHANNEL_LAYERS = {

    ‘default’: {

        ‘BACKEND’: ‘channels_redis.core.RedisChannelLayer’,

        ‘CONFIG’: {‘hosts’: [(‘127.0.0.1’, 6379)]},

    },

}

  1. Create a Consumer

# consumers.py

from channels.generic.websocket import AsyncWebsocketConsumer

import json

class ChatConsumer(AsyncWebsocketConsumer):

    async def connect(self):

        self.room_group_name = ‘chat_room’

        await self.channel_layer.group_add(self.room_group_name, self.channel_name)

        await self.accept()

    async def disconnect(self, close_code):

        await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

    async def receive(self, text_data):

        data = json.loads(text_data)

        message = data[‘message’]

        await self.channel_layer.group_send(

            self.room_group_name,

            {‘type’: ‘chat_message’, ‘message’: message}

        )

    async def chat_message(self, event):

        await self.send(text_data=json.dumps({‘message’: event[‘message’]}))

  1. Routing

# routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [

    re_path(r’ws/chat/$’, consumers.ChatConsumer.as_asgi()),

]

✅ Now Django can handle real-time WebSocket connections.


Option 2: Using Flask + Flask-SocketIO

  1. Install Flask-SocketIO

pip install flask-socketio

  1. Basic Flask WebSocket Example

from flask import Flask, render_template

from flask_socketio import SocketIO, send

app = Flask(__name__)

app.config[‘SECRET_KEY’] = ‘secret!’

socketio = SocketIO(app)

@app.route(‘/’)

def index():

    return render_template(‘index.html’)

@socketio.on(‘message’)

def handle_message(msg):

    print(‘Message:’, msg)

    send(msg, broadcast=True)

if __name__ == ‘__main__’:

    socketio.run(app)

  • Broadcasting sends messages to all connected clients, ideal for chat apps or notifications.

Frontend Integration

React + SocketIO Example

import { useEffect, useState } from ‘react’;

import io from ‘socket.io-client’;

const socket = io(‘http://localhost:5000’);

function ChatApp() {

  const [message, setMessage] = useState(”);

  const [chat, setChat] = useState([]);

  useEffect(() => {

    socket.on(‘message’, msg => setChat(prev => […prev, msg]));

  }, []);

  const sendMessage = () => {

    socket.emit(‘message’, message);

    setMessage(”);

  };

  return (

    <div>

      <h1>CuriosityTech Real-Time Chat</h1>

      <div>

        {chat.map((msg, idx) => <p key={idx}>{msg}</p>)}

      </div>

      <input value={message} onChange={e => setMessage(e.target.value)} />

      <button onClick={sendMessage}>Send</button>

    </div>

  );

}

export default ChatApp;

✅ This setup allows instant updates without page reloads.


Best Practices for WebSockets

  1. Use authentication – Secure connections with JWT or session tokens.
  2. Handle disconnects – Ensure users can reconnect gracefully.
  3. Limit message size – Avoid large payloads to reduce latency.
  4. Use Redis for scaling – When running multiple server instances.
  5. Monitor performance – Real-time apps can be resource-intensive.

Infographic Idea – WebSocket Flow

  • Visual representation shows full-duplex communication, unlike HTTP’s request-response.

Real-World CuriosityTech Example

  • Students at CuriosityTech built a real-time collaborative note-taking app:
    • Backend: Django Channels + Redis
    • Frontend: React SPA
    • Features: Live updates, multiple users editing same note, instant notifications
  • Outcome: Learners mastered real-time Python programming and understood WebSocket scaling concepts.

Conclusion

WebSockets transform Python Full Stack applications from static, request-based apps into dynamic, real-time experiences. Whether building chat apps, live dashboards, or collaborative platforms, mastering WebSockets is essential for modern Full Stack developers.

At CuriosityTech, students integrate WebSockets into full-stack projects, learning both theory and hands-on skills to excel in professional development scenarios.


Tags:

#Python #WebSockets #FullStackDevelopment #DjangoChannels #FlaskSocketIO #CuriosityTech #RealTimeApplications

Keywords:

Python WebSockets tutorial, Django Channels example, Flask SocketIO chat, real-time Full Stack Python, CuriosityTech projects

Leave a Comment

Your email address will not be published. Required fields are marked *