Reputation: 35
I am trying to run code after I return my template in flask
Here is sample code
@app.route("/hello")
def Hello():
thread = threading.Thread(target=long_running_task)
thread.start()
return 'hello'
def long_running_task():
time.sleep(5)
return redirect("/goodbye")
Is this possible? Why when this code is ran it does not work as intended? /hello should load, then after 5 seconds it should redirect, but it never redirects and I believe the thread is never ran.
Upvotes: 1
Views: 2162
Reputation: 6705
it does work, but since in your Hello
function you return 'Hello' after the thread start, the return redirect("/goodbye")
never makes it to the browser. But the processing in the background works, you can add some print statements in the long_running_task
code and see the flask console for yourself:
@app.route("/hello")
def Hello():
thread = threading.Thread(target=long_running_task)
thread.start()
return 'hello'
def long_running_task():
print("long task started")
time.sleep(5)
print("long task ended")
return redirect("/goodbye")
Upvotes: 3