Home > Software design >  Show GIF animation while time.sleep() in Flask
Show GIF animation while time.sleep() in Flask

Time:02-14

I want to display a GIF-File in a webpage while in the background (Flask-Application) is a time.sleep() function. This is my code: app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def test():
    #Do something    
    time.sleep(2)    
    #Do something different
    
    return render_template("template.html")

app.run()

template.html:

<title>Test</title>
<p>Finally loaded</p>

My goal is that while the 2 seconds waiting a GIF-File should be shown. I tried this:

<div id="preloader"></div>
<style>
  #preloader{
    background: white url(/static/animation.gif) no-repeat center center;
    background-size: 15%;
    height: 100vh;
    width: 100%;
    position: center;
    z-index: 1000;
    margin: auto;
    cursor: wait;
  }
</style>
<script>
  var loader = document.getElementById("preloader");
  window.addEventListener("load", function(){
    loader.style.display = "none"
  })
  window.onload = preloader;
</script> 
<p>Done</p>

..., but the gif file is only displayed (for a short time) after the countdown. Can anybody please help me?

CodePudding user response:

You cannot do this using only one endpoint because the time.sleep(2) blocks the response, so you only see the loading indicator after the sleep phase is finished. You need a separate endpoint for the task.

With some javascript we can call the task endpoint after the base page is loaded and during the request we can show the loading indicator. I'm using HTMX library here for the demonstration.

@app.route("/")
def index():
    # Base page that calls the task endpoint.
    return render_template("index.html")

@app.route("/task")
def task():
    time.sleep(2)
    return '<span>Done</span>'

index.html base template:

<script src="https://unpkg.com/[email protected]"></script>
<div hx-get="/task" hx-trigger="load">
    <img  src="/static/animation.gif" />
</div>

The two hx- attributes tells HTMX to load the /task endpoint on page load event and replace the innerHTML of the div element with the response. During the request, the indicator image will be visible, then it will be replaced with the response from /task.

  • Related