烧瓶,按1个处理请求 [英] Flask, processing requests 1 by 1

查看:50
本文介绍了烧瓶,按1个处理请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个flask应用程序,它监听一些工作.这个过程很长(让我们说1分钟),我不允许同时处理两个请求.

I have a flask application which listens for some job to do. The process is quite long (let us say 1 minute) and I would like not allow to process two requests at the same time.

如果收到请求,我可以关闭正在监听的端口烧瓶,并在完成后再次打开,我将非常高兴.另外,我可以设置一个信号灯,但不确定烧瓶如何同时运行.

I will be great if once I receive a request, I could close the port flask is listening to and open again when finish. Alternatively I could setup a semaphore but I am not sure about how flask is running concurrently.

有什么建议吗?

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')

推荐答案

您可以为此使用信号量:

You could use a semaphore for this:

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"

信号灯的用法是控制对公共资源的访问.

The semaphore usage is to control the access to a common resource.

您可以在此处

这个SO问题也可以在此处

This SO question can help you as well here

正如GeorgSchölly在评论中写道:在多种服务的情况下,上述解决方案是有问题的.

As Georg Schölly wrote in comment, The above mentioned solution is problematic in a situation of multiple services.

尽管如此,您可以使用wsgi来实现您的目标.

Although, you can use the wsgi in order to accomplish your goal.

@app.route("/",methods=['POST'])
def main_process():
    uwsgi.lock()
    # Critical section
    # heavy process here to run alone
    uwsgi.unlock()
    return "Done"

uWSGI支持可配置数量的锁,可用于同步工作进程

uWSGI supports a configurable number of locks you can use to synchronize worker processes

有关更多信息,请在此处

这篇关于烧瓶,按1个处理请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆