William Irvine
William Irvine

Reputation: 61

In Flask, can I show one template while a function runs and redirect to another once the function is complete?

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

Upvotes: 5

Views: 3516

Answers (1)

vidstige
vidstige

Reputation: 13079

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>

Upvotes: 7

Related Questions