Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected
Tutorial

Building a Live Dashboard That Updates Itself with Python and WebSockets

Learn to build a self-updating dashboard using Python's websockets library and Chart.js. This step-by-step tutorial walks you through creating a real-time data visualization that streams temperature and humidity data without page refreshes.

July 2026 6 min read 1 views 0 hearts

Building a Live Dashboard That Actually Updates Itself

You know that moment when you refresh a page to see if the data changed? It feels clunky, like checking your phone every few seconds for a text. Real-time dashboards solve that problem beautifully. Instead of refreshing, the data flows to you the moment something changes.

Today, I'll walk through building a live dashboard using Python on the backend and Chart.js in the browser. By the end, you'll have a dashboard that updates instantly, without any page reloads.

What Makes This Tick

The magic behind real-time updates is WebSockets. Think of them as a permanent open phone line between your browser and a Python server. Once connected, either side can send data whenever it wants. No more request-response dance. Just pure, continuous data flow.

On the Python side, we'll use websockets library to push data. On the frontend, plain JavaScript will catch those messages and feed them into Chart.js charts.

Setting Up the Python Server

Let's start with a simple WebSocket server. Save this as server.py:

import asyncio
import websockets
import json
import random
import time

async def data_stream(websocket, path):
    try:
        while True:
            # Simulate real-time sensor data
            data = {
                "temperature": round(random.uniform(20, 30), 1),
                "humidity": round(random.uniform(40, 70), 1),
                "timestamp": time.time()
            }
            await websocket.send(json.dumps(data))
            await asyncio.sleep(2)  # Send every 2 seconds
    except websockets.exceptions.ConnectionClosed:
        print("Client disconnected")

start_server = websockets.serve(data_stream, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

This server sends fake temperature and humidity readings every two seconds. In a real setup, you'd replace those random numbers with actual data from a database or an IoT device.

Building the HTML Dashboard

Now create index.html in the same folder:

<!DOCTYPE html>
<html>
<head>
    <title>Real-Time Dashboard – PythonSkillset</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <h1>Live Data Dashboard</h1>
    <div style="width: 600px; height: 400px;">
        <canvas id="tempChart"></canvas>
    </div>

    <script>
        const ctx = document.getElementById('tempChart').getContext('2d');

        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: 'Temperature (°C)',
                    data: [],
                    borderColor: 'rgb(255, 99, 132)',
                    tension: 0.1
                }]
            },
            options: {
                animation: false,
                scales: {
                    x: { display: true },
                    y: { beginAtZero: false }
                }
            }
        });

        const socket = new WebSocket('ws://localhost:8765');

        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            const time = new Date(data.timestamp * 1000).toLocaleTimeString();

            chart.data.labels.push(time);
            chart.data.datasets[0].data.push(data.temperature);

            // Keep only last 20 points to avoid memory issues
            if (chart.data.labels.length > 20) {
                chart.data.labels.shift();
                chart.data.datasets[0].data.shift();
            }

            chart.update();
        };

        socket.onerror = function(error) {
            console.log('WebSocket Error: ' + error);
        };
    </script>
</body>
</html>

Running It All Together

  1. First, install the required Python package:
pip install websockets
  1. Start the Python server in one terminal:
python server.py
  1. Open index.html in your browser. If double-clicking doesn't work, you might need to serve it via a simple HTTP server:
python -m http.server 8000

Then visit http://localhost:8000.

  1. Watch your dashboard come alive. Every two seconds, a new data point appears without any page refresh. The chart slides smoothly, always showing the last 20 readings.

Making It Your Own

This basic example is just the starting point. Here are a few ways to extend it:

  • Add more charts: Create separate charts for humidity, pressure, or any other metric. Each can listen to the same WebSocket and filter the data.

  • Store historical data: Instead of generating random numbers, have the server pull data from a SQLite or PostgreSQL database. You can then serve both the initial batch (for chart history) and stream new values.

  • Add interactivity: Buttons to pause/resume updates, change chart time ranges, or export data as CSV.

  • Handle reconnections: Add WebSocket reconnection logic in JavaScript so the dashboard survives server restarts gracefully.

Why This Works So Well

The beauty of this approach is its simplicity. Your Python server remains the single source of truth for data. The frontend doesn't need to know where the data comes from – it just renders what it receives in real time.

For teams at PythonSkillset building monitoring tools, this pattern scales nicely. You can have hundreds of browser clients all connected to one server, each seeing updates with minimal latency.

The next time someone asks for a "live dashboard," you'll know exactly how to deliver. No page refreshes. No polling. Just pure, streaming data that feels like magic.

Comments

Questions, corrections, and tips stay visible for everyone reading this page.

0 in thread

Join the discussion

Shown next to your comment.

Up to 4,000 characters

No comments yet

Be the first to leave a note — it helps the next reader.