'update pyserial data in real time with flask [duplicate]
im trying to see data in real time, i have to close the python program to refresh the data. It refreshes only when i close the python file and restart it. i want the data to refresh in real time.
from flask import Flask
import serial
app = Flask(__name__)
water = serial.Serial("COM4",9600)
water1 = water.readline().decode('ascii')
# @ signifies a decorator
@app.route('/')
def index():
return 'This is home page'
@app.route('/plant')
def plant():
while True:
return '<h2>soil is:</h2> ' + water1 + '%'
if __name__=="__main__":
app.run()
Solution 1:[1]
It depends on what you mean by "real-time". Let us take a look at how Flask works first.
Why it doesn't work
Everything outside of the functions with @app.route
decorator gets executed only once, upon the start of the server. That is why your data is currently fetched just once, your data fetching code is outside those functions:
water = serial.Serial("COM4",9600)
water1 = water.readline().decode('ascii')
Refresh data on page refresh
Now, the easiest way how to fix it is to fetch the data each time you refresh the page like this:
@app.route('/plant')
def plant():
water = serial.Serial("COM4",9600)
water1 = water.readline().decode('ascii')
# while True: // don't use while True though, it'll freeze your program forever.
return '<h2>soil is:</h2> ' + water1 + '%'
Since plan()
is executed upon each page refresh, your data also updates such.
Refresh data in "real" real-time
There is the third option though, to achieve the result that usually is called "real-time". You won't get around it without using Javascript though. In this case you set up an API, which will return your data, which you'll call from Javascript.
I, however, suspect, that what you really want to do is refresh data on page refresh.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |