2016-08-03 2130 views
-1

我想直播一些數據,比如我的房子的溫度來自Raspberry Pi。我可以收集數據,但是如何在不刷新的情況下更新頁面?我聽說過AJAX和JavaScript,但我不知道如何將它用於Flask。從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> 

編輯:我已經看到了這個解決方案enter link description here

但我不明白的地方我必須把JS代碼,而且我如果我用這個解決方案,jsonify(TEMP = TEMP)剛剛打印的頁面上:`

{ 
     "temp": 31.2 
} 

所以我只是想一些吃茶,在此先感謝和美好的夜晚:p

+0

http://flask.pocoo.org/docs/0.11/patterns/jquery/ – davidism

回答

0

根據使用javascript的時間,傳遞數據和定期更新可能是最容易的。

+0

我該如何在JavaScript中做到這一點?而這個JavaScript代碼是正確的還是不要更新數據? –