创建Flask实时仪表板

时间:2019-04-29 18:09:20

标签: python python-3.x flask

我正在开发天气Web应用程序,该应用程序将使用从Raspberry Pi传感器BME680收集的数据,将其推送到数据库中,并将其进一步推送到Web仪表板。这是我有的问题: 1.根据我下面的代码,将数据同时从传感器推送到仪表板和数据库,或者从传感器将数据导入数据库,再从数据库提要进一步馈送到Web仪表板,是否更聪明? 2.根据以下两个代码,是否可以将它们组合到一个烧瓶应用程序中?

到目前为止,我已经设法创建了从传感器收集数据并将其推入数据库的代码。我也有烧瓶应用程序,它将从数据库中提取数据并将最后一个值推送到仪表板。我试图将我的数据收集代码与flask应用程序结合起来,使其每秒将数据推送到Web仪表板。

这是用于将数据从Sensor收集到数据库中的代码

# Import Dependencies
import sqlite3
import time
import board
from busio import I2C
import adafruit_bme680
import datetime
# Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)
# change this to match the location's pressure (hPa) at sea level
bme680.sea_level_pressure = 1013.25
# Define database name to which data will be stored
dbname = 'Sensors.db'
# Using while loop capture the data in variables and store it in database
while True:    
    # Create the now variable to capture the current moment
    now = datetime.datetime.now()
    TEMPERATURE = round(bme680.temperature,1)
    GAS = round(bme680.gas,1)
    HUMIDITY = round(bme680.humidity,1)
    PRESSURE = round(bme680.pressure,1)
    ALTITUDE = round(bme680.altitude,1)
    TIME_STAMP =(now)

    conn = sqlite3.connect(dbname)
    curs = conn.cursor()
    curs.execute("INSERT INTO BME_DATA (TIME_STAMP, TEMPERATURE, GAS, 
    HUMIDITY, PRESSURE, ALTITUDE) values(?,?,?,?,?,?)",(TIME_STAMP, 
    TEMPERATURE, GAS, HUMIDITY, PRESSURE, ALTITUDE))
    conn.commit()
    # Test by printing data from table BME_DATA
    #for row in curs.execute("SELECT * FROM BME_DATA"):   
        #print (row)
    conn.close()    
    time.sleep(1)

这是烧瓶应用程序的代码,它将从数据库中获取数据:

from flask import Flask, render_template, request
app = Flask(__name__)
import sqlite3
# Retrieve data from database
def getData():
    conn=sqlite3.connect('../Sensors.db')
    curs=conn.cursor()
    for row in curs.execute("SELECT * FROM BME_DATA ORDER BY TIME_STAMP 
     DESC LIMIT 1"):
        Time = str(row[1])
        Temperature = row[2]
        Gas = row[3]
        Humidity = row[4]
        Pressure = row[5]
        Altitude = row[6]

    conn.close()
    return Time, Temperature, Gas, Humidity, Pressure, Altitude
# main route 
@app.route("/")
def index():    
    Time, Temperature, Gas, Humidity, Pressure, Altitude = getData()
    templateData ={'Time': Time,
        'Temperature': Temperature,
        'Gas': Gas,
        'Humidity': Humidity,
        'Pressure': Pressure,
        'Altitude': Altitude}
    return render_template('index.html', **templateData)
if __name__ == "__main__":
   app.run(debug=False)

所以要运行此代码,我必须同时运行两个代码,并且在页面上得到的只是打开页面时传感器值的最后读取。为了获得更新,我必须按下按钮并在flask中调用查询。那么,如何结合这两个工具来制作一个烧瓶应用程序,该应用程序将收集数据并不断将数据推送到仪表板?

我已经对此进行了研究,我认为必须使用库socketio来做到这一点。

0 个答案:

没有答案