Reputation: 1657
In route request in Flask, how do I trigger a thread to start and have it continue right away to the next line. In the code below, how do I get the print "Onto the next already" to occur right after the new thread is spawned, rather than wait the ~10 sec for it to finish?
Thanks!
def consumer(searchValue,assignedUniqueID):
print "Searching..."
print "Running thread! Args:", (searchValue, assignedUniqueID)
time.sleep(10)
print "Done!"
@app.route('/_search')
def add_numbers():
assignedUniqueID = str(uuid.uuid4())
Thread(target=consumer(searchValue,assignedUniqueID)).start()
print "Onto the next already"
return jsonify(result="33434443",
assignedUniqueID = assignedUniqueID
)
Upvotes: 0
Views: 1126
Reputation: 77359
Sorry, this is more a comment than an answer, I'm posting here because it is a bit large for the comment system.
This kind of bug can be hard to track in Flask given their extensive use of thread-local storage and other magic.
In web applications multitasking is often handled by the use of queues instead of threads, with the web application queing tasks and background daemons (workers) doing the job. This approach scales a lot better:
Specially popular are solutions involving AMQP or Key/Value databases like redis or memcached. For AMQP in Python, take a look at celery, I use it a lot in combination with Django.
Upvotes: 1