gpt4 book ai didi

python - 使用 Flask 在 Python 中进行长轮询

转载 作者:太空狗 更新时间:2023-10-29 20:28:23 29 4
gpt4 key购买 nike

我正在尝试在 Flask 框架下使用 JQuery 和 Python 进行长轮询。

之前在 PHP 中做过长轮询,我尝试以同样的方式去做:

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

因此,在我的 ini.py 中,我创建了一个到/poll 的 app.route 供 JQuery 调用。 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"

问题是,当上面的代码开始轮询时,服务器似乎过载并且其他 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();

}
});

}

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

提前致谢!! :)

最佳答案

正如link @Robᵩ 提到,你的 flask 应用程序只是重载。这是因为 Flask 应用程序在使用 app.run() 运行时默认处于单线程模式,因此它每次只能处理一个请求。

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

if __name__ == '__main__':
app.run(threaded=True)

或者使用像 gunicorn 或 uwsgi 这样的 WSGI 服务器来为 flask 提供多重处理:

gunicorn -w 4 myapp:app

希望您喜欢 Python 和 Flask!

关于python - 使用 Flask 在 Python 中进行长轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29517223/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com