【问题标题】:How to make Flask/ keep Ajax HTTP connection alive?如何使 Flask/保持 Ajax HTTP 连接处于活动状态?
【发布时间】:2023-03-21 14:57:01
【问题描述】:

我有一个 jQuery Ajax 调用,如下所示:

    $("#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 方法:

@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 对话框:

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 回复时不使用 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": [...]}

真的没有实现keep-alive吗?

【问题讨论】:

    标签: ajax flask keep-alive werkzeug


    【解决方案1】:

    默认的 request_handler 是 WSGIRequestHandler。

    app.run()前,加一行, WSGIRequestHandler.protocol_version = "HTTP/1.1"

    别忘了from werkzeug.serving import WSGIRequestHandler

    【讨论】:

      【解决方案2】:

      Werkzeug 的集成 Web 服务器基于 Python 标准库的 BaseHTTPServer 构建。如果您将其 HTTP 协议版本设置为 1.1,BaseHTTPServer 似乎支持 Keep-Alives。

      Werkzeug 不这样做,但如果您准备好侵入 Flask 用来实例化 Werkzeug 的 BaseWSGIServer 的机器,您可以自己进行。请参阅调用werkzeug.serving.run_simple()Flask.run()。你必须做的归结为BaseWSGIServer.protocol_version = "HTTP/1.1"

      我还没有测试解决方案。我想你确实知道 Flask 的 Web 服务器应该只用于开发。

      【讨论】:

      • 确实,集成的网络服务器仅用于开发目的。
      • 我昨天显然很累;我没有注意到我得到了 1.0 的回复。 :/我会看看,看看能做些什么。谢谢。
      • 答案为我指明了正确的方向,但我必须设置WSGIRequestHandler.protocol_version = "HTTP/1.1"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2021-09-13
      • 2013-08-27
      • 2019-09-01
      • 2013-03-20
      • 1970-01-01
      相关资源
      最近更新 更多