使用Flask进行Python长轮询

mic*_*zer 9 python long-polling flask

我正在尝试使用Flask Framework在JQuery和Python上进行长时间的轮询.

在PHP之前完成了长时间的轮询,我试图以同样的方式进行:

具有while(true)循环的脚本/函数,定期检查更改,例如数据库中每0.5秒,并在发生更改时返回一些数据.

所以在我的ini .py中我创建了一个app.route to/poll for JQuery to call.JQuery为它提供了有关客户端当前状态的一些信息,并且poll()函数将其与数据库中当前的状态进行了比较.循环结束并在观察到变化时返回信息.

这是python代码:

@app.route('/poll')
def poll():
client_state = request.args.get("state")

    #remove html encoding + whitesapce from client state
    html_parser = HTMLParser.HTMLParser()
    client_state = html_parser.unescape(client_state)
    client_state = "".join(client_state.split())

    #poll the database
    while True:
        time.sleep(0.5)
        data = get_data()
        json_state = to_json(data)
        json_state = "".join(data) #remove whitespace

        if json_state != client_state:
            return "CHANGE"
Run Code Online (Sandbox Code Playgroud)

问题是,当上面的代码开始轮询时,服务器似乎被重载和其他Ajax调用,而其他请求,如使用JQuery将"加载"图像加载到html是无响应和超时.

为了完成起见,我在这里包含了JQuery:

function poll() {

queryString = "state="+JSON.stringify(currentState);

$.ajax({
    url:"/poll",
    data: queryString,
    timeout: 60000,
    success: function(data) {
        console.log(data);
        if(currentState == null) {
            currentState = JSON.parse(data);
        }
        else {
            console.log("A change has occurred");
        }

        poll();

    },
    error: function(jqXHR, textStatus, errorThrown) {

        console.log(jqXHR.status + "," + textStatus + ", " + errorThrown);

        poll();

    }
});

}
Run Code Online (Sandbox Code Playgroud)

这需要多线程还是什么?或者有没有人知道我为什么会遇到这种行为?

提前致谢!!:)

kxx*_*ing 6

就像链接@Rob?提到,你烧瓶应用程序只是超载。这是因为在运行时app.run(),flask 应用程序默认处于单线程模式,因此每次只能处理一个请求。

您可以通过以下方式启动多线程:

if __name__ == '__main__':
    app.run(threaded=True)
Run Code Online (Sandbox Code Playgroud)

或者使用像 gunicorn 或 uwsgi 这样的 WSGI 服务器来为具有多处理功能的烧瓶提供服务:

gunicorn -w 4 myapp:app
Run Code Online (Sandbox Code Playgroud)

希望你喜欢 Python 和 Flask!

  • 一般来说,尽管 WSGI 应用程序不适合任何规模的长轮询,但这同样适用于 PHP。这是因为使用 WSGI 时的 Python 和 PHP 都是同步系统,需要一个进程或线程来处理每个请求。因此,要处理大量并发的长轮询请求,您需要大量的容量(进程或线程)。长轮询最好使用异步 Web 服务器和框架来实现。 (2认同)