Make function not to wait for other function inside it

坚强是说给别人听的谎言 提交于 2020-01-25 04:19:08

问题


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.


回答1:


Maybe working with subproccesses is what you need? You can try something like:

import subprocess

subprocess.call(func1())



回答2:


I think the problem is in the POST method, that you prescribed. Also 100 seconds sleep time too long :)

def func1():
    print("Print function executed1")
    time.sleep(10)
    print("Print function executed2")

app = Flask(__name__)

@app.route("/first")
def main():
    print("Request received1")
    func1()
    print("Request received2")
    return json.dumps({"status": True})

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

Output:

Request received1
Print function executed1
Print function executed2
Request received2



回答3:


After receiving/executing a request for function 1, you can set/reset a global status flag/variable(e.g. flag_func_1 = True:Request Received ; False:Request Executed).

You can monitor the value of the flag_func_1 and can return {"status": True}immediately after setting flag.

Ex: inside main function you can do something like :

if(flag_func_1 == True):
  func_1()
  flag_func1 = False


来源:https://stackoverflow.com/questions/59213379/make-function-not-to-wait-for-other-function-inside-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!