如何使Flask /使Ajax HTTP连接保持活动状态? [英] How to make Flask/ keep Ajax HTTP connection alive?
问题描述
我有一个jQuery Ajax调用,像这样:
I have a jQuery Ajax call, like so:
$("#tags").keyup(function(event) {
$.ajax({url: "/terms",
type: "POST",
contentType: "application/json",
data: JSON.stringify({"prefix": $("#tags").val() }),
dataType: "json",
success: function(response) { display_terms(response.terms); },
});
我有这样的Flask方法:
I have a Flask method like so:
@app.route("/terms", methods=["POST"])
def terms_by_prefix():
req = flask.request.json
tlist = terms.find_by_prefix(req["prefix"])
return flask.jsonify({'terms': tlist})
tcpdump显示HTTP对话框:
tcpdump shows the HTTP dialog:
POST /terms HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://127.0.0.1:5000/
Content-Length: 27
Pragma: no-cache
Cache-Control: no-cache
{"prefix":"foo"}
但是,Flask无需保持活动状态即可答复。
However, Flask replies without keep-alive.
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 445
Server: Werkzeug/0.8.3 Python/2.7.2+
Date: Wed, 09 May 2012 17:55:04 GMT
{"terms": [...]}
是真的吗
推荐答案
Werkzeug的集成Web服务器基于Python标准库的BaseHTTPServer构建。如果将HTTPHTTP协议版本设置为1.1,则BaseHTTPServer似乎支持Keep-Alives。
Werkzeug's integrated web server builds on BaseHTTPServer from Python's standard library. BaseHTTPServer seems to support Keep-Alives if you set its HTTP protocol version to 1.1.
Werkzeug不会这样做,但是如果您准备入侵Flask用于实例化Werkzeug的BaseWSGIServer的机器,则可以自己完成。请参见 Flask.run()
,该调用调用 werkzeug.serving.run_simple()
。您要做的事情归结为 BaseWSGIServer.protocol_version = HTTP / 1.1
。
Werkzeug doesn't do it but if you're ready to hack into the machinery that Flask uses to instantiate Werkzeug's BaseWSGIServer, you can do it yourself. See Flask.run()
which calls werkzeug.serving.run_simple()
. What you have to do boils down to BaseWSGIServer.protocol_version = "HTTP/1.1"
.
我尚未测试解决方案。我想您确实知道Flask的网络服务器应仅用于开发。
I haven't tested the solution. I suppose you do know that Flask's web server ought to be used for development only.
这篇关于如何使Flask /使Ajax HTTP连接保持活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!