2017-02-19 135 views
3

我有烧瓶应用程序,它倾听一些工作要做。这个过程很长(让我们说1分钟),我不想同时处理两个请求。烧瓶,处理请求1 by 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') 
+0

你是如何运行烧瓶刨?直接通过烧瓶还是将它作为WSGI模块运行? –

+0

我正在使用wsgi模块 – mosh442

+1

在这种情况下,它可能会更复杂一点。一个WSGI服务器(取决于配置)可以并行产生多个进程,但是Python的锁只能跨线程工作,而不能跨越进程。您需要引入可以锁定的共享资源。这可能是数据库,文件或共享锁,例如[named semaphore](http://stackoverflow.com/q/2798727)。 –

回答

1

你可以使用一个信号量这样的:

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" 

信号灯的使用是控制访问的公共资源。

你可以看到有关信号的详细信息在这里enter link description here

这太问题可以帮助你以及enter link description here

编辑:

正如乔治·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

+0

如果有多个进程,这不起作用。这里的锁不适用于多个进程,这是Web服务器的正常配置。 –

+0

@GeorgSchölly,感谢您的评论,我添加了关于您评论的编辑部分。 –

0

你可以尝试添加threading.Lock表明,一些工作已经在进行中:

import threading 
from contextlib import ExitStack 

busy = threading.Lock() 
@app.route("/",methods=['POST']) 
def main_process(): 
    if not busy.acquire(timeout = 1): 
     return 'The application is busy, refresh the page in a few minutes' 

    # ensure busy.release() is called even if an exception is thrown 
    with ExitStack() as stack: 
     stack.callback(busy.release) 
     # heavy process here to run alone 

    return "Done" 

但是烧瓶中默认允许一次(更多信息here)要处理的只有一个要求,所以如果你在处理单个请求的过程中没有问题,那么所有其他用户的页面在加载完成之前都不会被加载(甚至可能发生请求超时错误),所以你不需要改变任何东西。
如果您想让其他用户收到一条消息,例如上面的代码,请将工作人员数量增加到2,以便当一个工作人员处理请求时,另一个工作人员将阻止其他用户。

+0

如果没有锁,这很容易出现竞争状况。 –

+0

@GeorgSchölly好点。编辑为使用锁 – Leva7

+0

如果有多个进程,这不起作用。这里的锁不适用于多个进程,这是Web服务器的正常配置。 –