使用 Python 的 Flask 多线程

Str*_*eem 3 flask

我只是想知道是否可以在 Flask 服务器上同时启动两个功能?我需要function_1在它触发后启动function_2并同时运行这两个功能。是否可以?

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)
Run Code Online (Sandbox Code Playgroud)

小智 6

是的你可以。您只需要导入threading模块。

import threading

def function1():
    # your code here

def function2():
   # your code here
Run Code Online (Sandbox Code Playgroud)

您可以这样启动线程:

threading.Thread(target=function1).start()
threading.Thread(target=function2).start()
Run Code Online (Sandbox Code Playgroud)

两者将同时生活

你可以在那里找到很好的教程获得进一步的解释:)