How to make Flask / keep Ajax HTTP connection live?

I have a jQuery Ajax call, for example:

    $("#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); },
      });

I have a Flask method, for example:

@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 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"}

However, Flask responds without saving.

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": [...]}

Is it really that keep-alive is not implemented?

+5
source share
2 answers

The integrated Werkzeug web server is based on BaseHTTPServer from the Python standard library. BaseHTTPServer seems to support Keep-Alives if you set the HTTP protocol version to 1.1.

Werkzeug , , Flask Werkzeug BaseWSGIServer, . . Flask.run(), werkzeug.serving.run_simple(). , , BaseWSGIServer.protocol_version = "HTTP/1.1".

. , , - Flask .

+6

request_handler WSGIRequestHandler.

app.run() , WSGIRequestHandler.protocol_version = "HTTP/1.1"

from werkzeug.serving import WSGIRequestHandler.

+14

All Articles