OK so I am still struggling on this one. Here is my complete code after using @JohnMcCabe's suggestion. I have 3 files, the first one is my Python file that merely gets the local time.
import datetime
import time
now = datetime.datetime.now()
print(now)
If I set this file up as:
import datetime
import time
while True:
now = datetime.datetime.now()
print(now)
time.sleep(2)
It refreshes and gets me the date every 2 seconds. But when it's imported in to my Flask project it takes over and just will not load the web page.
So I use the first version of the file that gets the local time. Next I have my Flask Python page:
from flask import Flask, render_template, request, jsonify
from flask_bootstrap import Bootstrap
import Timereppper
import datetime
now = datetime.datetime.now()
app = Flask(__name__)
Bootstrap(app)
@app.route('/')
def hello():
return render_template('hello.html', myvar= now.second)
@app.route('/currentstatus')
def currentstatus():
return render_template('hello.html', myvar= now.second)
@app.route('/historic')
def historic():
return render_template('historic.html')
@app.route('/data')
def get_data():
mbdata = Timereppper.now() # Call your code that gets the data here
return jsonify(mbdata) # And return it as JSON
if __name__ == '__main__':
app.run(host= 'localhost', port=5000, debug=False, threaded=True)
And then I have my main hello.html file with the code suggested by @JohnMcCabe at the bottom. This returns the text on the bottom of the main webpage "New Data Goes Here" and if I look at localhost:5000/data, I get the date that was read when the Flask server was first started. I want this date to update continuously or every few seconds and display on the main home page of the website. Can anyone show me where I am going wrong? I apologize I am new to Flask.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Vibration Monitor</title>
<meta name="viewport" content="width=device-wi dth, initial-scale=1">
<link href="{{url_for('static', filename='css/bootstrap.min.css')}}"
rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico')
}}">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>window.jQuery || document.write('<script src="{{
url_for('static', filename='jquery.js') }}">\x3C/script>')
</script>
</head>
<nav class="navbar navbar-expand-lg navbar-light bg-#808080">
<a class="navbar-brand" href= https://www.iotindustries.co.uk>
<img src="/static/img/IOT Industries Logo 1THIN.png" width="300" height="90"
class="d-inline-block" alt="">
</a>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link font-weight-bold" href="/currentstatus">Current
Status</a>
</li>
<li class="nav-item active">
<a class="nav-link font-weight-bold" href="/historic">Historic</a>
</li>
</ul>
</nav>
<div class="alert alert-secondary" role="alert"></div>
<div class="card-deck" style="width: 42rem;">
<div class="card text-white bg-dark mb-3" style="width: 16rem;">
<img class="card-img-top" src="/static/img/vibes1.png" alt="Vibration
Image">
<div class="card-body">
<h5 class="card-title">Current vibration level:</h5>
<h1 class="card-text font-weight-bold">15 mA</h1>
<a class="btn btn-success">Acknowledge</a>
</div>
</div>
<div class="card text-white bg-dark mb-3" style="width: 16rem;">
<img class="card-img-top" src="/static/img/timer.svg" alt="Timer Image">
<div class="card-body">
<h5 class="card-title">Estimated days until failure:</h5>
<h1 class="card-text font-weight-bold"> 3 Days {{myvar}} </h1>
<a class="btn btn-info" href="/historic">View Historic</a>
</div>
</div>
</div>
<body>
<div id="myDataDiv">New Data Goes Here</div>
</body>
<script>
var goGetNewData = function() {
$.ajax({
url: '/data',
dataType: 'json',
type: 'get',
success: function(e) {
$('#myDataDiv').html('New Data ' + e);
},
error: function(e) {
$('#myDataDiv').html('Error');
},
});
}
var waitTime = 10; // 10 seconds
var fetchInterval = window.setInterval(goGetNewData, waitTime*1000);
</script>
</html>
I have a Python file which is constantly reading a Modbus register every couple of seconds, using the Python time.sleep() function. This value is getting logged to a Google Firebase database.
What I would like to do is display this value read from the ModBus register on my Flask website. I just don't know how to do it. Am I able to either:
Get the updated ModBus value from the Python file, pass that in to MyFlaskApp.py continuously or at the click of a button in my HTML file.
Query the Firebase database and get this to display the latest written value either continuously or at the click of a button.
Which, if any of these, can be done and what would be the best method? Can anyone post an example of how I would be able to do this?
Well if you want to do it on a click of a button, you can make the button part of an HTML form and have it POST to your Flask application:
@app.route('/update')
def val():
return render_template("index.html",data=data)
This would work, considering the value you want to pass to the HTML is called data.
To display the data passed through, your html should look like this:
<p>{{data}}</p>
Instead of updating the modbus value every two seconds, you could do it only when the button is clicked like so:
@app.route('/update')
def val():
# code to get the value
return render_template("index.html", data=data)
This way everytime you click the form button to get a new value, then the data is read from the database. Instead of using another file as an import and using datetime, this would make sure that your program not only saves memory but still returns the desired value.
In the now method, you should write to a txt file as such:
# get the data
f = open("mod.txt", w+)
f.write(data)
f.close()
Then when you receive the button click in the Flask app:
@app.route('/update')
def val():
f = open("mod.txt", r)
data = f.read()
f.close()
return render_template("index.html", data=data)
To make sure that the other program is running, you can do this:
if __name__ == '__main__':
execfile('modbusreginfo.py')
app.run(host='localhost', port=5000, debug=False, threaded=True)
If you want to make the page reload every 2 seconds so there is no button click, you can add this to your html:
<meta http-equiv="Refresh" content="2">