0

I want to live stream some data such as the temperature of my house from a Raspberry Pi. I can collect the data, but how do I update the page without a refresh? I heard about AJAX and JavaScript but I don't know how to use it with Flask.

from flask import Flask, request, make_response, abort, redirect, render_template, jsonify

app = Flask(__name__)

tempc = 0.0
temp_sensor = "/sys/bus/w1/devices/28-000007013b3f/w1_slave"

def temp_raw():
    f = open(temp_sensor, "r")
    lines = f.readlines()
    f.close()
    return lines

def read_tempc():
    lines = temp_raw()
    temp = lines[1].strip()[-5:]
    tempc = float(temp)/1000
    tempc = round(tempc, 1)
    return tempc

@app.route('/temp', methods = ['GET'])
def temp():
    temp = read_tempc()
    return render_template('temp.html', temp=temp)
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>"Test Temperature</title>
    </head>

        <body>
                <h1> Je suis ici </h1>
                <p> La température de la pièce est de: {{ temp }}°.</p>
                <script text = "text/javascript">
                        function() {
                                $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
                                $.getJSON($SCRIPT_ROOT+"/temp",
                                        function(data) {
                                                $("#getTemp").text(data.temp+"°")
                                        });
                                };
                </script>
        </body>
</html>

EDIT: I already saw this solution enter link description here

But I don't understand where I have to put the Js code and moreover I if I use this solution, the jsonify(temp=temp) just print that on the page: `

{
      "temp": 31.2
}

So I just want some explications, thanks in advance and good evening :p

0

1 Answer 1

-2

It's probably easiest to pass the data and do periodic updates according to time using javascript.

1
  • And how can i do that in javascript ? And this javascript code is right or not to do an update of the data ?
    – flmd
    Aug 3, 2016 at 16:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.