Flask 多线程与 Python

标签 flask

我只是想知道是否可以在 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/

相关文章:

python - 使用 Flask 接收 gzip

Python Flask自动生成的Swagger/OpenAPI 3.0

http - flask 发送文件 : how do I know if I need "as_attachment"?

python - 如何使用 Flask test_client 上传多个文件?

css - 在 CSS <Style> 标签中使用 Flask 模板

python - 如何将 postman 的不记名 token 读入 Python 代码?

flask - 实现日期选择器和 Flask-WTForms

Python Flask 未返回 MySQL 请求的有效响应

python - 使用 Flask 在 Elastic APM for Python 中设置(自定义)字段

python - Flask 中的嵌套蓝图?