Nik.clgn
Nik.clgn

Reputation: 53

Update variable in the background

so I'm currently writing a Flask application and I am new to flask. There is some processing going on, which I outsourced to a separate function. As this processing takes some time, I wanted to give the user a progress update on how many iterations have passed. No problem so far. However, as soon I call the render template, the function ends and I cannot update that variable anymore. I was imagining an if loop. if that variable changes, render template with the new variable as input. But after the first iteration, the if loop will brake. Currently, the render template renders an html function, which just displays the variable it receives. I want to update that variable as soon as it changes.

Do you guys have any suggestion, on how I could achieve this "background update"?

Cheers and thanks!

Upvotes: 0

Views: 673

Answers (1)

charlemagne
charlemagne

Reputation: 322

You need some kind of ongoing request/response cycle. As soon as your app sends the response with the rendered template back to the browser, this connection is closed and there's no way to send any more data.

There's a few things that need to happen in order to accomplish what you want:

  1. The long running function needs to run in the background so it doesn't block execution of the rest of the application
  2. There has to be a way to get a status update from the long running function
  3. The client (ie browser) needs a way to receive the status updates

1 and 2 can be solved using celery. It allows you to run tasks in the background and the task to send information via a side channel to be consumed elsewhere.

The easiest way to achieve 3 would be to set up a route in your flask application that returns information about the task, and request it periodically from the browser using some JavaScript. The more favorable method in my opinion would be to use websockets to actively send out the information to the client, but this is a bit more complicated.

This is just a rough outline, but there's a tutorial by Miguel Grinberg about how to set this up using celery and polling from JS.

Upvotes: 2

Related Questions