问题
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 forfunc1
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