Hello, fellow members of the Stack Overflow community
I am currently working on a function in Flask that updates a variable via a POST request and then processes this variable to display it on a website, similar to how sports live score websites function.
While the website is functioning as intended, I have plans to scale up and accommodate more users. I believe it would greatly enhance user experience if the website updated in real-time whenever the variable var_g changes, rather than the current setup where it updates every 2 seconds. Additionally, it would be fantastic if all users could receive the update simultaneously. I'm hoping for some guidance from the experts here.
Any suggestions or advice would be immensely valuable, as I am still relatively inexperienced and may be making mistakes in my approach.
Flask side
from flask import Flask, jsonify, render_template, request
# Global variable to keep everything updated
var_g = 0
app = Flask(__name__)
# Handling the POST request
@app.route('/read', methods=['GET', 'POST'])
def read():
if request.method == 'POST':
# Extracting the data to update from the headers of the POST request
info = int(request.headers.get('info'))
# Updating the global variable to reflect the changes
global var_g
var_g = info
print(var_g)
# Processing the data
if var_g == 0:
color = "No color"
elif ( var_g > 0 and var_g < 100 ):
color = "red"
elif ( var_g >= 100 ):
color = "blue"
else:
color = "Unknown"
print(color)
return jsonify(color = color)
# Index route
@app.route('/', methods=['GET'])
def index():
if request.method == 'GET':
return render_template('index.html')
HTML side
<html>
<head>
<title> State of colors </title>
</head>
<body>
<p> The current color state is </p>
<!-- Displaying the results from the /read function -->
<p> <span id=results> --- </span> </p>
<!-- Using JSON, jQuery, AJAX for real-time updates -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type=text/javascript>
function colors() {
$.getJSON('/read',
// Retrieving the updated color
function(data) {
// Displaying the results from the JSON response
$("#results").text(data.color);
});
// Automatically updating every 2 seconds
setTimeout(function() {
colors();
}, 2000);
}
// Initiate the function on page load
window.onload = colors;
</script>
</body>
</html>