Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 586
Eddie Huang Avatar asked Oct 27 '25 10:10

Eddie Huang


2 Answers

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

like image 173
methane Avatar answered Oct 30 '25 00:10

methane


This example working as you want (tested on Python 3.4.3)

from time import sleep
from concurrent.futures import ThreadPoolExecutor

# DOCS https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
executor = ThreadPoolExecutor(2)


@app.route('/index')
def index():
    executor.submit(do_sth_else)
    print('ready to response')
    return render_template('index.html')


def do_sth_else():
    print("Task started!")
    sleep(10)
    print("Task is done!")
like image 39
Denys Synashko Avatar answered Oct 30 '25 00:10

Denys Synashko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!