Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a loading gif to the page when a function runs in the background in Flask?

I have written a Flask app that displays a page with a button, when the user clicks on that button a Python function is called which does some processing (which usually takes about 2 minutes). After this processing is over, a new page opens displaying the results. Now I want to include a 'loading gif' that indicates the user that the processing is in progress. How do I do this? Here is an example of what my code looks like.

app.py

from flask import Flask, render_template
 import time

 app = Flask(__name__)

 @app.route('/')
 def index():
     return render_template('index.html')

 @app.route('/result', methods=['POST'])
 def result():
     time.sleep(5) # indicates the time delay caused due to processing
     return render_template('result.html')

 if __name__ == '__main__':
     app.run(debug=True)

index.html

<html>
    <body>
        <form method=post action="/result">
            <input type=submit value='Start Processing' name='submit_btn'>
        </form>
    </body>
</html>

result.html

<html>
    <body>
        <h1> Processing Done </h1>
    </body>
</html>
like image 613
Harshith Bolar Avatar asked Dec 05 '22 15:12

Harshith Bolar


1 Answers

This needs to be done on the client side only.

Add jquery in your header section:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Add this to your submit button code:

onclick="$('#loading').show();"

Get a loading.gif image Add below code after your form in html

<div id="loading" style="display:none;"><img src="loading.gif" alt="" />Loading!</div>

References: 1 2

like image 105
Priyank Mehta Avatar answered Dec 08 '22 03:12

Priyank Mehta