Streem
Streem

Reputation: 628

Flask Multithreading with Python

I am just wondering is it possible to start two functions to work in same time with Flask server? I need to start function_1 after it trigger function_2 and run both functions in same time. Is it possible?

def function_1():
    yield "start_function_2"
    counter = 0
    while True:
       counter += 1
       print counter


def function_2():
    second_counter = 0
    while True:
       second_counter += 1
       print second_counter

def main():
    return render_template("index.html")

@app.route("/start_functions", methods=["POST"])
def start_functions():
    data = request.data
    if request.method == "POST":
        for i in function_1(data):
           if (i == "start_function_2"):
              function_2()

if __name__ == "__main__":
    app.run(dhost="0.0.0.0", port=port)

Upvotes: 3

Views: 12379

Answers (1)

r34d
r34d

Reputation: 136

Yes you can. You just need to import the threading module.

import threading

def function1():
    # your code here

def function2():
   # your code here

You start threads like this:

threading.Thread(target=function1).start()
threading.Thread(target=function2).start()

Both will live at the same time

You can find nice tutorial over there for further explanations :)

Upvotes: 8

Related Questions