Building a Website Analytics System with Python Sockets
- Published on
- 4 min read
- Authors
- Name
- Robin te Hofstee
- @Robin_teHofstee
Tutorial for building a website analytics system using a Python socket server and a web dashboard. This tutorial will include:
✅ Full explanation of each line in the Python server
✅ Step-by-step guide for the website code
✅ How to send requests and process responses
✅ How to display analytics on a web dashboard
I’ll structure it into sections:
1️⃣ Setting Up Your Python Server
2️⃣ Handling HTTP Requests Correctly
3️⃣ Logging Visitor Analytics
4️⃣ Building a Dashboard (HTML + JavaScript)
5️⃣ Integrating Everything
1️⃣ Setting Up Your Python Server
Your server will use sockets to communicate with the website, log visits, and return analytics.
Server Code:
import json
import socket
import threading
from datetime import datetime
PORT = 5050 # Port number where the server listens
SERVER = "localhost" # Server hostname
ADDR = (SERVER, PORT) # Address tuple
FORMAT = "utf-8" # Encoding format
LOG_FILE = "analytics.json" # File to store analytics data
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a TCP socket
server.bind(ADDR) # Bind the socket to an address
server.listen() # Start listening for incoming connections
Explanation:
socket.AF_INET
: Uses IPv4.socket.SOCK_STREAM
: Uses TCP (for reliable communication).server.bind(ADDR)
: Binds the server tolocalhost:5050
.server.listen()
: Makes the server wait for connections.
2️⃣ Handling HTTP Requests Correctly
We modify the server to accept POST and GET requests.
Handling Client Requests:
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} Connected")
request = conn.recv(1024).decode(FORMAT) # Receive request from client
if not request:
conn.close()
return
# Handling POST requests from the website
if request.startswith("POST /send_message"):
body = request.split("\r\n\r\n")[-1] # Extract message body
log_visit(addr, body) # Log user visit
response = (
"HTTP/1.1 200 OK\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n"
"\r\n"
"Message received successfully!"
)
conn.sendall(response.encode(FORMAT))
# Handling GET requests for analytics
elif request.startswith("GET /get_analytics"):
conn.sendall(get_analytics().encode(FORMAT))
conn.close()
Explanation:
conn.recv(1024).decode(FORMAT)
: Reads the HTTP request.request.startswith("POST /send_message")
: Detects a POST request.request.split("\r\n\r\n")[-1]
: Extracts the body data.log_visit(addr, body)
: Saves visitor data to analytics.conn.sendall(response.encode(FORMAT))
: Sends an HTTP response.
3️⃣ Logging Visitor Analytics
Each visit is recorded in analytics.json
.
Logging Function:
def log_visit(client_addr, page):
data = {"ip": client_addr[0], "page": page, "timestamp": str(datetime.now())}
try:
with open(LOG_FILE, "r") as file:
logs = json.load(file)
except FileNotFoundError:
logs = []
logs.append(data)
with open(LOG_FILE, "w") as file:
json.dump(logs, file, indent=4)
Explanation:
- Saves visitor info in
analytics.json
with IP, page, and timestamp. - Uses
json.dump(logs, file, indent=4)
to make data readable.
4️⃣ Building a Dashboard (HTML + JavaScript)
Your website will have a simple dashboard to display analytics.
Website Code:
<!DOCTYPE html>
<html>
<head>
<title>Website Analytics Dashboard</title>
<script>
async function fetchData() {
let response = await fetch("http://localhost:5050/get_analytics");
let data = await response.json();
document.getElementById("logs").innerHTML = data.map(log =>
`<tr><td>${log.ip}</td><td>${log.page}</td><td>${log.timestamp}</td></tr>`
).join("");
}
</script>
</head>
<body onload="fetchData()">
<h1>Website Analytics Dashboard</h1>
<table border="1">
<tr><th>IP Address</th><th>Page Visited</th><th>Timestamp</th></tr>
<tbody id="logs"></tbody>
</table>
</body>
</html>
Explanation:
fetch("http://localhost:5050/get_analytics")
: Calls Python server..then(response => response.json())
: Converts data to JSON.document.getElementById("logs").innerHTML = ...
: Updates table dynamically.
5️⃣ Integrating Everything
Now, let's start the server.
Final Server Code:
def start():
print("[SERVER STARTED] Tracking analytics...")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
start()
Explanation:
while True
: Keeps the server running forever.server.accept()
: Waits for a new connection.threading.Thread(target=handle_client, args=(conn, addr))
: Starts a new thread to handle the request.
Testing Everything
1️⃣ Run your Python server:
python server.py
2️⃣ Open your browser and visit the dashboard. 3️⃣ Send a message using:
fetch("http://localhost:5050/send_message", {
method: "POST",
headers: { "Content-Type": "text/plain" },
body: "Hello, Python Server!"
});
4️⃣ The server logs the visit. 5️⃣ Open the analytics dashboard:
http://localhost:5050/get_analytics
6️⃣ Your website displays visitor stats.
🎯 Final Thoughts
✔ Works with raw sockets—no Flask needed
✔ Tracks visitors and logs analytics
✔ Displays analytics in a live web dashboard
✔ Handles both POST
and GET
requests correctly
🚀 Now you have a working website analytics system! 😊🔥