0

I have a Flask server, and something like that:

@app.route("/page", methods=['GET', 'POST'])
def page():
    is_working = False
    if (request.method == 'POST'):
        is_working = True
        do_long_task()
        is_working = False
    return render_template('page.html', is_working)

do_long_task is a process that can took some time. I want to alter the template considering if the process is running or not. With the example above the server simply wait for do_long_task() to finish to render the template. I ideally would like something like this:

@app.route("/page", methods=['GET', 'POST'])
def page():
    is_working = False
    if (request.method == 'POST'):
        is_working = True
        render_template('page.html', is_working)
        do_long_task()
        is_working = False
        render_template('page.html', is_working)

But this won't work because the template once rendered must be returned (and thus page must finish) to be taken into account.

How can I do that ?

Bellerofont
  • 1,081
  • 18
  • 17
  • 16
  • @Sergey's answer seems to address your problem, but i'll rather use JavaScript to fetch the data asynchronously. – danidee Jan 19 '17 at 17:21
  • How can you do that? Do you make Flask and Javascript communicate? How? If you mean work only with Javascript, that is not possible as do_long_task is something already implemented in Python and too big to be changed. –  Jan 20 '17 at 09:10

1 Answers1

0

The easiest way to do it is to use Flask Streaming. This answer provides several examples how to do it. Note that it is not rerendering the page but sending additional data which need to be inserted on client side.

Community
  • 1
  • 1
Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36