Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi forum,

a colleague of mine has created a marvellous piece of HTML and CSS that leaves me astonished what UIs are possible with web programming skills.

I am responsible for the backend in python. I have a connection to a real-world measurement device and have received values from that device that reside in variables. Now I want to push those values onto the UI. For that, I shall use my colleague's work as template and put some javascript in where the values shall get visible.

I'm a noob to python and its whole ecosystem. Within the application I have
Python
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)

def HandleNewMeasurement(measurement):
    socketio.send({"Value":measurement})

What's the minimal viable javascript that I am supposed to put in the HTML template so above measurement will be visible on the UI?

What I have tried:

I shamelessly stole from a how-to Minimal socket.io example[^] on GitHub
Python
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:8000');

    socket.on('connect', function() {
        console.log('connected to server');
        socket.send('I am here.');
    });

    socket.on('message', function(obj) {
        console.log('received a message!');
        var msg = JSON.parse(obj)
        // console.log(msg);
        if (msg['Measurement'])
        {
            console.log(msg['Measurement']);
            document.writeln(msg['Measurement']);
        }
    });

    socket.on('disconnect', function() {
        console.log('disconnected from server');
    });

</script>
I guess what I'm looking for is in the socket.on('message' part. Somehow the socketio.send() call from the question part shall connect to it. Or should it be socketio.emit()? I read both and cannot tell which one does what yet.

How do I get a value onto the UI that changes when the backend sends new data?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900