Answer the question
In order to leave comments, you need to log in
How to run a function and continue the work of the main program without waiting for its completion?
The bottom line is, there is a script using Flask in the main() function, under a certain condition, the function() function is launched. I need this function to start working when called, but at the same time, the main function returns the value value without waiting for the function () to complete. I so understood, it is necessary to use asynchronous programming. Tried to use asyncio but didn't work for me.
import ...
app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)
@app.route("/", methods=['POST', 'GET'])
def main():
value = a + b
if value >=2:
fucntion()
return value
app.run()
Answer the question
In order to leave comments, you need to log in
If done in a human way, then of course Celery.
But if you don't want to fence the garden with Celery and the main thing for you is to run the function, then you can put it in a separate file and run it through subprocess
For example, put two files side by side.
from flask import Flask
import subprocess
app = Flask(__name__)
@app.route("/")
def main():
subprocess.Popen('python mysleep.py', shell=True, executable='/bin/bash')
return "Hello"
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
import time
time.sleep(10)
print("zzzzzzzzzzzz")
Flask is designed to be single-threaded and synchronous, using multi-threading or asynchrony can lead to problems. Use Celery and the like.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question