2

Is it possible to update my flask app UI's render template in a while loop?

I have already tried multiple times to return the render_template within my while loop to update the web ui every time the while loop runs.

@app.route('/test_try')
def test_try:
    list = []
    count = 0
    list_count = 10

    while count < list_count:
        list.append('new_count'+str(count))
        count += 1

    return render_template('test_try.html', list=list)

I would like my web ui (test_try.html) to update with every count += 1 that runs through the while loop. For example, right now it updates the 10 runs, but all at the some time. I would like to incrementally update each run until the count reaches 10.

I have tried to render_template within the while loop, but that doesn't seem to work either.

  • It’s not clear what you’re trying to do here. Do you want the page to load 10 times in a row somehow? Can you explain more about the behavior you’re looking for and why you want it? The answer is likely to be that you need to use JS and not Flask for this. – Nick K9 Aug 26 '19 at 18:08
  • I have an app in which returns client information based on api calls. I have a set number of api calls that I am trying to run, 10 calls, with every API call return, I want the information on the page to update. Currently, I am able to run all 10 calls and have the page update them all at the same time, but I would like to update them individually. For example, if there is a response status 200 or response status 404, I want the web up to update them incrementally instead of all at once. – CaliforniaDataSurfer Aug 26 '19 at 18:11

1 Answers1

1

Once the request has been responded to, there is no way for Flask to affect the content of the page without receiving another request. So you can’t just respond a bunch of times as each API call returns.

The behaviour you’re looking for requires JavaScript. You can see some options here for how to deal with pushing data from the server to the client.

If you are OK with kicking off the requests from the client side, you could also set up a series of AJAX calls which will return as the server succeeds in fetching the data from the API.

But a question you should ask yourself is: what is the server adding to this setup? Why isn’t the client just calling the API directly and updating the page as needed when the API returns?

Nick K9
  • 3,885
  • 1
  • 29
  • 62