使功能不等待其中的其他功能 [英] Make function not to wait for other function inside it

查看:43
本文介绍了使功能不等待其中的其他功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 flask 服务,如下所示:

从烧瓶导入烧瓶中的

 ,请求导入json导入时间app = Flask(__ name__)@ app.route("/first",Methods = ["POST"])def main():打印(收到请求")func1()返回json.dumps({"status":True})def func1():时间.睡眠(100)打印(执行打印功能")如果__name__ =="__main__":app.run("0.0.0.0",8080) 

现在,当我使用 http://localhost:8080/first

  • 控制权转至main方法,它打印接收到请求,并等待 func1 执行,然后返回 {"status":True}

但是现在我不想等待 func1 完成执行,而是将发送 {"status":True} func1 将继续执行.

解决方案

为了回复flask的请求,您需要完成修饰的功能(在您的情况下,这是 main )./p>

如果要并行执行某项,则需要在另一个线程或进程中执行.多进程应用程序用于实现多个CPU.(受CPU限制);在您的情况下,您只需要并行执行它即可,因此最好使用线程.

一种简单的技术是使用ThreadPool.从 concurrent.futures 导入 ThreadPoolExecutor ,然后对其进行提交,这将使您的函数执行代码得以继续.试试这个:

从烧瓶导入烧瓶中的

 ,请求导入json导入时间导入操作系统从current.futures导入ThreadPoolExecutorapp = Flask(__ name__)#任务管理器执行器_threadpool_cpus = int(os.cpu_count()/2)执行程序= ThreadPoolExecutor(max_workers = max(_threadpool_cpus,2))@ app.route("/first",Methods = ["POST"])def main():打印(收到请求")EXECUTOR.submit(func1)返回json.dumps({"status":True})def func1():time.sleep(2)打印(执行打印功能")如果__name__ =="__main__":app.run("0.0.0.0",8080) 

这将在另一个线程中运行 func1 ,从而使flask能够在不阻塞用户的情况下响应用户,直到完成 func1 为止.

I have a flask service as below:

from flask import Flask, request
import json
import time


app = Flask(__name__)

@app.route("/first", methods=["POST"])
def main():
    print("Request received")

    func1()

    return json.dumps({"status": True})


def func1():
    time.sleep(100)
    print("Print function executed")


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

So now when I make a request using http://localhost:8080/first

  • control goes to main method and it prints Request received and wait for func1 to get executed and then it returns {"status": True}

But now I don't want to wait for func1 to finish its execution instead it will sent {"status": True} and func1 will continue it's execution.

解决方案

In order to reply to request from flask, you need the decorated function to finish (in your case, that's main).

If you want to execute something in parallel, you need to execute it in another thread or a process. Multi-process apps are used to achieve more than a single CPU. (CPU bound); in your case, you just need it to execute in parallel so it is better to go with threads.

A simple technique is to use ThreadPool. import ThreadPoolExecutor from concurrent.futures, then submit work to it, which allows your function execution code to continue. Try this:

from flask import Flask, request
import json
import time
import os
from concurrent.futures import ThreadPoolExecutor


app = Flask(__name__)


# Task manager executor
_threadpool_cpus = int(os.cpu_count() / 2)
EXECUTOR = ThreadPoolExecutor(max_workers=max(_threadpool_cpus, 2))


@app.route("/first", methods=["POST"])
def main():
    print("Request received")
    EXECUTOR.submit(func1)
    return json.dumps({"status": True})


def func1():
    time.sleep(2)
    print("Print function executed")


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

This will run the func1 in a different thread, allowing flask to respond the user without blocking until func1 is done.

这篇关于使功能不等待其中的其他功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆