5

Basically I want to show a loading page while a time-consuming process takes place and then redirect to my complicated other page.

  • 1
    Similar question: https://stackoverflow.com/questions/24251898/flask-app-update-progress-bar-while-function-runs – Laurent LAPORTE May 17 '18 at 21:35
  • It depend how long your time-consuming process take, but simple way for relative short wait is to show loading overlay/modal in your template and call directly the page processing the result. Your browser will wait flask response during process and keep showing your loading animation. – Calumah May 17 '18 at 23:15

1 Answers1

7

While not impossible to achieve, I recommend using javascript for this task.

Here is a small example. First lets write a very simple flask server, with one very slow endpoint.

from flask import Flask, render_template, jsonify
app = Flask(__name__)

@app.route("/")
def hello():
    return render_template('redirect.html')

@app.route("/done")
def done():
    return "Done!"

@app.route("/slow")
def slow():
    import time
    time.sleep(5)
    return jsonify("oh so slow")

if __name__ == "__main__":
    app.run()

Now, we can make a beautiful user experience by invoking the endpoint from javascript instead. Save it as templates/redirect.html as per usual.

<html>
  <head>
    <script>
      function navigate() {
        window.location.href = 'done';  // redirect when done!
      }
      fetch('slow').then(navigate); // load the slow url then navigate
    </script>
  </head>
  <body>
    Loading...  <!-- Display a fancy loading screen -->
  </body>
</html>
vidstige
  • 12,492
  • 9
  • 66
  • 110
  • could you explain the expected behavior of your code please. – Sai Pardhu Jul 22 '21 at 18:57
  • If you first read the question, and the my answer in full it should be perfectly clear what it does. If still in doubt, please try to run it! :) Only two files needed. If you have further questions after this, please comment again with a more specific question and I will try to answer. – vidstige Jul 28 '21 at 19:57
  • Comon man, don't you think I didn't do that. I just don't understand after I ran the same code on my browser i.e. what is the page that is being loaded during the function's run time and what is being show after the completion – Sai Pardhu Aug 05 '21 at 17:14
  • 1
    When you load the page the "Loading..." text is show, and then after five seconds you get redirected to a new page that says "Done!". – vidstige Aug 07 '21 at 12:45
  • 1
    It first loads `redirect.html`. On that page, javascript activates that fetches the `/slow` route. Once that is done, it navigates to the `/ done` page. – Danferno Apr 27 '22 at 08:55