我只是想知道是否可以在 Flask 服务器上同时启动两个功能?我需要在触发 function_2
后启动 function_1
并同时运行这两个函数。可能吗?
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)
最佳答案
是的,你可以。您只需要导入 threading
模块。
import threading
def function1():
# your code here
def function2():
# your code here
你像这样开始线程:
threading.Thread(target=function1).start()
threading.Thread(target=function2).start()
两者将同时存在
你可以找到很好的教程over there进一步的解释:)
关于Flask 多线程与 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44144598/