Home > Blockchain >  Flask - display variable dynamically
Flask - display variable dynamically

Time:04-14

In app.py, the code is as follows:

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
    count = 1
    while 1:
        count  =1
        return render_template('index.html', count=count)
  
if __name__ == '__main__':
    app.run()

I want to display the variable 'count' in the index.html. In the index.html, the code is as follows

{{count}}

May I know how can I pass the variable 'count' from app.py to index.html, so that the variable 'count' can be updated dynamically? (I tried to use the library 'flask_socketio', but I need to change 'app.run()' to 'socketio.run(app)' when running. This seems to be not a good way since it complicates all the code. Is there a simple way for me to update the data?)

Thank you.

CodePudding user response:

Every time request comes to the route, 2 is getting returned. Because return in while disrupts the counter (acts like a break). Either make it a global variable, or increment it in the flask app context.

Which means either

count = 1

@app.route("/")
def hello_world():
    global count
    count  = 1
    return render_template('index.html', count=count)

or something like (I don't use flask daily, so there probably could be a better solution):

from flask import Flask, render_template, current_app

app = Flask(__name__)
with app.app_context():
    current_app.config["count"] = 1


@app.route("/")
def hello_world():
    current_app.config["count"]  = 1
    return render_template("index.html", count=current_app.config["count"])

This solution solves a problem when you want to update the counter value on each request. In case if you want to have a "live counter" it's more a javascript thing. But yes, if you want to "stream" some more complicated data than just an integer, websockets are the choice.

CodePudding user response:

def index():
  if "count" not in session:
   session['count'] = 0
  elif "count" in session:
    while session["count"] < 5:
      x = session["count"]   1 
      session["count"] = x
      return render_template("index.html", count = session["count"])
  return render_template("index.html", count = session["count"]) 

This is my approach, socketio is somehow the cleanest approach to this. (Or Ajax mixed with this, or pure ajax).

  • Related