A real-time dashboard powered by Flaxon's streaming data capabilities with live chart updates.
from flaxon import Flaxon, StreamingResponse
import asyncio
import json
import random
import time
app = Flaxon("dashboard-backend")
@app.get("/api/stream")
async def stream_data():
async def generate():
while True:
data = {
"price": round(random.uniform(100, 200), 2),
"timestamp": time.time(),
"volume": random.randint(50, 500),
}
yield f"data: {json.dumps(data)}\n\n"
await asyncio.sleep(1)
return StreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
}
)
@app.get("/api/stats")
async def get_stats():
return {
"updates": 0,
"latency": "0ms",
"points": 0,
"memory": "0MB",
}
// Live chart with Chart.js
const ctx = document.getElementById('price-chart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Price',
data: [],
borderColor: '#3b82f6',
backgroundColor: 'rgba(59,130,246,0.1)',
fill: true,
tension: 0.4,
}]
},
options: {
responsive: true,
plugins: {
legend: { display: false }
},
scales: {
x: { grid: { display: false } },
y: { grid: { color: 'rgba(255,255,255,0.05)' } }
}
}
});
// EventSource connection
const eventSource = new EventSource('/api/stream');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
chart.data.labels.push(new Date(data.timestamp).toLocaleTimeString());
chart.data.datasets[0].data.push(data.price);
if (chart.data.labels.length > 60) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update('none');
};