Eddie Huang Eddie Huang - 1 year ago 138
Python Question

Threading not working in flask

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

def index():
t = threading.Thread(do_sth_else())
print('ready to response')
return render_template('index.html')

def do_sth_else():
print('sth else done')

When calling
in the browser, the result in the server console is not what I expected:

sth else done
ready to response

I want the
function to run in some other thread, while the
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
    function kept waiting until
    is finished

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


Answer Source

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).