``When in Flask, updating a website is done solely upon the change of variables

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>

Answer №1

According to @charlietfl's suggestion, the best way to send notifications from the server to the client upon state update is by utilizing WebSocket. While flask may not be ideal for this due to its requirement of one thread per request, transitioning to asyncio could be a more efficient alternative. The aiohttp library provides support for both HTTP and websocket servers seamlessly.

Here is a sample code to demonstrate how this could be implemented (note that adjustments may be needed and the code has not been tested):

import asyncio
import aiohttp.web

your_state_here = {'counter': 0}

active_clients = []

async def index(request):
    return aiohttp.web.Response(text='<your template here>')


async def do_update(request):
    # your logic here

    your_state_here['counter'] += 1

    for ws in active_clients:
        ws.send_str('updated %s' % your_state_here['counter'])

    return aiohttp.web.Response(text='Ok')


async def on_state_update(request):
    ws = aiohttp.web.WebSocketResponse()
    await ws.prepare(request)

    active_clients.append(ws)

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            if msg.data == 'close':
                active_clients.remove(ws)
                await ws.close()

    return ws


def main():
    loop = asyncio.get_event_loop()
    app = aiohttp.web.Application(loop=loop)
    app.router.add_route('GET', '/', index)
    app.router.add_route('POST', '/do_update', do_update)
    app.router.add_route('GET', '/updates', on_state_update)
    aiohttp.web.run_app(app, port=3000)


if __name__ == '__main__':
    main()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send the entire image to an API route in Next.js so that I can save it using FS and then upload it to Cloudinary?

I have a form here that utilizes React Hook Form. I'm wondering what I need to pass to the API endpoint via fetch in order to write an image to disk using fs, retrieve its location, and then send that location to Cloudinary. In the body of the fetch ...

The functionality of AngularJS ng-model seems to be disrupted when it is set within a directive

Is it possible to automatically generate the ng-model of an input based on the name of the input itself? This requirement arises from using Html.TextBoxFor in MVC, which creates the necessary name for binding the input to the server-side model. To streamli ...

Cookies are not being sent in the Ajax/Jquery request

I am utilizing the blueimp/jQuery-File-Upload script for facilitating cross-domain (subdomain) uploads. The primary page is www.example.com while the files are being uploaded to st2.example.com. While everything seems to be working well, I encounter an is ...

When attempting to extract values from selected items in Nextjs, clicking to handle them resulted in no action

I am facing an issue with my Nextjs project. I am trying to gather values from select items and combine them into a single object that needs to be processed by an API. However, when I click the select button, nothing happens. How can I resolve this issue? ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

Using Leaflet JS to implement multiple waypoints on a map

I am trying to create a route with multiple waypoints without hardcoding any data. My waypoints array should dynamically include latitude and longitude values. How can I achieve this? var data = [ { "title": 'Chennai', " ...

Can you explain the term 'outer' in the context of this prosemirror code?

Take a look at this line of code from prosemirror js: https://github.com/ProseMirror/prosemirror-state/blob/master/src/state.js#L122 applyTransaction(rootTr) { //... outer: for (;;) { What does the 'outer' label before the infinite loop ...

Create an excel spreadsheet using HTML tables with the help of jQuery

Upon clicking a button, I aim to generate an excel sheet. Essentially, I am trying to achieve what is being discussed here (Kalle H. Väravas answer). If the following links are not working within Mozilla browser, then maybe my code requires ActiveXObject ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

Retrieve all data in JSON format using Flask SQLAlchemy

I'm currently working on fetching and serializing user data from my database, but I've encountered an issue where I can only retrieve one user at a time. Here's the serialize method I'm using: def serialize(self): return { ...

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

Is there a way to implement word wrapping in li text without making any changes to its width

Is there a method to wrap the content inside li elements without modifying their width? As an illustration, consider the following structure - <ul> <li>Text Example</li> <li>Text Example</li> <li>Text Exampl ...

Invoking the HTML method from a WCF service

Currently, I am utilizing a callback in my WCF service to receive raw frames from the camera. I am currently working on developing an HTML application that will showcase these frames. However, my current approach involves using a button click event in HTM ...

Requesting a resource using the HTTP GET method returned no data

Looking to process the response from an http-request using JavaScript? Check out this straightforward example below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

Send information to Laravel using Ajax, including an array in the response

I am currently working on a webpage that uses AJAX to send data, including text and arrays as variables. Here is an example of my code: var data = { 'action':action, 'main_phase':main_phase, 'secondary_phase ...

How can I access my API by connecting Node.js to MongoDB remotely?

I have been working on developing an application using Node.js, Express, and MongoDB. I followed some teamtreehouse tutorials to set up Node.js and MongoDB on a Digital Ocean Server. However, when trying to access my API through various URL variations, I e ...

JavaScript (jQuery) module that fetches libraries

Many of you may be familiar with Google's API, which allows you to load specific modules and libraries by calling a function. The code snippet below demonstrates how this can be done: <script type="text/javascript" src="//www.google.com/jsapi"> ...

Issue with Chrome extension's popup not displaying

I was developing a chrome extension, but I encountered an issue where the popup does not display when clicking on the icon. After researching online, I found suggestions to change page_action to browser_action. However, even after making this adjustment, ...