我有一个Flask应用程序,它监听一些工作。这个过程很长(让我们说1分钟),我不允许同时处理两个请求。
如果一旦收到请求,我可以关闭正在监听的端口烧瓶,并在完成后再次打开,我将非常高兴。另外,我可以设置一个信号灯,但是我不确定烧瓶如何同时运行。
有什么建议吗?
from flask import Flask, request
app = Flask(__name__)
@app.route("/",methods=['GET'])
def say_hi():
return "get not allowed"
@app.route("/",methods=['POST'])
def main_process():
# heavy process here to run alone
return "Done"
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0')
Run Code Online (Sandbox Code Playgroud)
您可以为此使用信号量:
import threading
import time
sem = threading.Semaphore()
@app.route("/",methods=['POST'])
def main_process():
sem.acquire()
# heavy process here to run alone
sem.release()
return "Done"
Run Code Online (Sandbox Code Playgroud)
信号量的用途是控制对公共资源的访问。
您可以在此处查看有关信号量的更多信息
这个SO问题也可以在这里帮助你
编辑:
正如 Georg Schölly 在评论中所写,上述解决方案在多个服务的情况下是有问题的。
虽然,您可以使用 wsgi 来实现您的目标。
@app.route("/",methods=['POST'])
def main_process():
uwsgi.lock()
# Critical section
# heavy process here to run alone
uwsgi.unlock()
return "Done"
Run Code Online (Sandbox Code Playgroud)
uWSGI 支持可配置数量的锁,可用于同步工作进程
有关更多信息,请阅读此处