0

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
               )
1
  • aside from the unresolved searchValue name you're passing around without defining in your example, this code looks like it should do what you're asking for. Can you post a little more information? Do you get an error? May 20, 2013 at 1:50

1 Answer 1

1

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:

  • workers can live in other machines
  • the number of workers running in parallel is easier to control than the number of running threads. I've seen even small traffic surges bringing a server to a halt when using threads.
  • it is easier to synchronize and or handle concurrency

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.