0

I want to know how to return render_template('start-crawl.html') and have a function run at the same time. Once the function completes I want to return render_template('finish-crawl.html').

from flask import Flask, render_template, request, make_response, redirect, url_for
from flask_executor import Executor

app = Flask(__name__)
executor = Executor(app)
has_ran = False

@app.route('/', methods=["POST", "GET"])
def index():
  if request.method == "POST":
     usr_input = form["usr_input"]
     def func():
        """
        some code
        global has_ran
        has_ran = True
        """

     executor.submit(func)
     try:
       return render_template('start-crawl.html')
     finally:
       x = 5 # Use this variable for loop but other than that it is useless
       while x == 5:
          if has_ran:
            return render_template('finish.html')

  else:
    return render_template('index.html')

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

How I want this code to function is when func() is called through executor.submit(func), it starts running it and while it's running return render_template('start-crawl.html'). After executor.submit(func) finishes, it return render_template('finish.html'). Currently what happens is when I press submit on the form, the page keeps loading and then return render_template('finish.html') without return render_template('start.html'). What is the problem here?

  • I think you could use JS for this task because if you'll wait untill your task complete you'll freeze your entire app and you cannot render anything in between. – Chiheb Nexus Nov 29 '20 at 23:22
  • @ChihebNexus, Can you explain how I could use Javascript to achieve the desired outcome because I'm not so good with it. –  Nov 30 '20 at 00:30
  • 1
    See this section of `flask_executor` [docs](https://github.com/dchevell/flask-executor#futures) – Chiheb Nexus Nov 30 '20 at 00:43
  • https://stackoverflow.com/questions/68344462/python-flask-executor-how-to-pass-results-from-a-background-task-to-a-currentl this kicks off a background task using executor. You also look at sockets to emit pass variables from backend to frontend https://stackoverflow.com/questions/68411571/flask-socketio-emitting-a-pandas-dataframe-from-a-background-task-using-flask. – Sade Jul 19 '21 at 14:19

0 Answers0