[FIXED] Python Flask Executor | How to pass results from a background task to a currently active html page

Issue

To set up a simple HTML frontend and a Python flask back-

  • Create an html script (index.html) and save it in D:\Projects\test_backgroundtask\templates\views
  • 
        
    Test Background Task
    1. Create a Python script and save D:\Projects\test_backgroundtask:

    Code

    Import pandas as pd
    from Flask import Flask, render_template, request
        
        
        app = Flask(__name__)
        
        
            
        @app.route('/', methods=['GET'])
        Def index():
            return render_template('views/index.html')
        
        @app.route('/post', methods=['POST'])
        Differential post ():
            return "received: {}".format(request.form)
        
        if __name__ == "__main__":
            app.run( port = '5004')
     

    To create background tasks, flask has a package called flask_executor.
    Updated Python script to create background using Excutor

     from Flask import Flask, render_template, request
        import pandas as pd
        fromflask_executor import executor
        global input_val
        
        app = Flask(__name__)
        
        def background_task_func(input_val):
            If input_val==1:
                data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}
                test_val = pd.DataFrame(data)
            Print (test_val)
            
        @app.route('/', methods=['GET'])
        Def index():
            global input_val
            input value=1
            executor.submit(background_task_func,input_val)
            return render_template('views/index.html')
        
        @app.route('/post', methods=['POST'])
        Differential post ():
            return "received: {}".format(request.form)
        
        if __name__ == "__main__":
            executor = executor (app)
            app.run( port = '5004')
     

    desired output:

    Once the results are complete, you will see a table containing the test_val.

    Note: The html page index.html is currently being viewed by the user, and other tables have already been viewed. The user is also interacting with other buttons on this page.

    Additional Information

    Note: I am using Django inside in my HTML script.

    Example used to toggle between tables or buttons:

     
     

    Solution

    Python script

    from flask import Flask, render_template, request
    import pandas as pd
    from flask_executor import Executor
    global input_val
    global test_val
    app = Flask(__name__)
    
    def background_task_func(input_val):
        global test_val
        data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}  
        test_val= pd.DataFrame(data)
        if test_val.shape[0]>1:
            print(test_val)
            return render_template('views/index.html',tables=[test_val.to_html(classes='data')])
        
    @app.route('/', methods=['GET'])
    def index():
        executor.submit(background_task_func,input_val)
        return render_template('views/index.html',tables=[test_val.to_html(classes='data')])
    
    @app.route('/post', methods=['POST'])
    def post():
        return "recived: {}".format(request.form)
    
    if __name__ == "__main__":
        data ={'Name': [], 'Age': []}  
        test_val= pd.DataFrame(data)
        input_val=1
        executor = Executor(app)
        
        app.run( port = '5004')
    

    Html code

    <html>
        <section>
          <div>
            <h>Test background task</h>
          </div>
          
          <div id="demofeatDIV" class="w3-container">
            <table class="w3-table-all w3-tiny">
                <tbody>
                <tr><th>Results</th></tr>
                {% for table in tables %}
                     {{ table|safe }}
                {% endfor %}
                </tbody>
           </table>
           <br>
         </div> 
        </section>
    </html>
    

    For a simple test example , this method will be fine. However, if there are other data being displayed, the disadvantage of using this method is that I need to refresh the entire page, this results in reloading the previous tables. The alternative solution is to use sockets. My solution in Flask socketio | Emitting a pandas dataframe from a background task using Flask executor to an Html script resolve this issue.

    Answered By – Sade

    Answer Checked By – Mildred Charles (Easybugfix Admin)

    Leave a Reply

    (*) Required, Your email will not be published