简体   繁体   中英

Take variable from a Python file and display in Flask

OK so I am still struggling on this one, here is my complete code after using @DrAgon suggestion. I have 3 files, the first one is my Python file that merely get 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 @DrAgon at the bottom. This returns the text on the bottom of the main webpage "New Data Goes Here" and if I look at lcalhost:5000/data I get the date that was read at the 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 anyne show me where I am going wrong. I apologise 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 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:

  1. 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.

  2. 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?

Thanks

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 recive 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">

Here's one way.

You will need to create 2 routes in your MyFlaskApp.py

  1. /home - This route will render an HTML template
  2. /data - This route will return JSON (containing the data from your ModBus file OR from querying Firebase)

(you can name the routes whatever you want)

In the HTML template returned by the first route you will need a div (with an id) to render the data and some JavaScript to continuously fetch new data.

Then just point the Ajax GET at your /data endpoint and your on your way.

 <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> 

The /data route could look something like this.

from flask import jsonify
import Modbusreginfo  # Import your other python code

@app.route('/data')
def get_data():
  mbdata = Modbusreginfo.getModBusData()  # Call your code that gets the data here
  return jsonify(mbdata)  # And return it as JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM