As others have mentioned, there are specialized tools to do this (celery seems to be the best), but if someone just wants to quickly get something set up and working, here is my approach which only uses Python's multiprocessing
module:
from flask import Flask
from multiprocessing import Process
import time
app = Flask(__name__)
def detachedProcessFunction(wait_time):
i=0
while i<wait_time:
i = i+1
print "loop running %d" % i
time.sleep(1)
@app.route('/start')
def start():
global p
p = Process(target=detachedProcessFunction, args=(15))
p.start()
return render_template('layout.html')
if __name__ == '__main__':
app.run(debug=True)
NOTE: This method won't work for running object functions (e.g. obj.objFunc()
). You will get an EOFError: Ran out of input inside a class
. In this case, you should create the object inside a non-object/standalone function and pass the arguments you need to create the object. For more info see here