Eddie Huang Eddie Huang - 3 months ago 39
Python Question

Threading not working in flask

I'm trying to use threading in my flask app, like:

@app.route('/index')
def index():
t = threading.Thread(do_sth_else())
t.start()
print('ready to response')
return render_template('index.html')

def do_sth_else():
time.sleep(5)
print('sth else done')


When calling
127.0.0.1:5000/index
in the browser, the result in the server console is not what I expected:

sth else done
ready to response


I want the
do_sth_else()
function to run in some other thread, while the
index()
function go on returning the response right away, which means I should see the above result in defferent order.

So I want to know:


  1. Why the
    index()
    function kept waiting until
    do_sth_else()
    is finished

  2. How do I get the app working as I wanted



Thanks!

Answer

t = threading.Thread(do_sth_else()) calls do_sth_else() and pass it's result to Thread. You should use it like t = threading.Thread(do_sth_else).

Comments