我有一个 flask 应用程序,它监听一些工作要做。这个过程很长(比如说 1 分钟),我不想同时处理两个请求。
如果一旦我收到一个请求,我就可以关闭 flask 正在监听的端口,并在完成后再次打开。或者我可以设置一个信号量,但我不确定 flask 是如何同时运行的。
有什么建议吗?
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')
最佳答案
你可以为此使用信号量:
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"
信号量的用途是控制对公共(public)资源的访问。
您可以在 here 中查看有关信号量的更多信息
这个 SO 问题也可以帮助您 here
编辑:
正如 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"
uWSGI 支持可配置数量的锁,您可以使用这些锁来同步工作进程
有关更多信息,请阅读 here
关于python - Flask,处理请求 1 by 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42325105/