5

I want to crate Keep-Alive http connection, but i failed.

I build a demo app.

from flask import Flask, make_response, Response
from flask import jsonify

try:
    from http.server import BaseHTTPRequestHandler
except: 
    from BaseHTTPServer import BaseHTTPRequestHandler

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    resp = make_response("{'123':'aaa'}")
    return resp

if __name__ == '__main__':
    BaseHTTPRequestHandler.protocol_version = "HTTP/1.1"
    app.run()

I send some requests,:

{"text":-1193959466}
{"text":-1139614796}
{"text":837415749}
{"text":-1220615319}
{"text":-1429538713}
{"text":118249332}
{"text":-951589224}

and i received some error:

127.0.0.1 - - [18/Apr/2019 20:14:15] "POST / HTTP/1.1" 200 -
127.0.0.1 - - [18/Apr/2019 20:14:16] "{"text":-1193959466}POST / HTTP/1.1" 405 -
127.0.0.1 - - [18/Apr/2019 20:14:16] "{"text":-1139614796}POST / HTTP/1.1" 405 -
127.0.0.1 - - [18/Apr/2019 20:14:17] "{"text":837415749}POST / HTTP/1.1" 405 -
127.0.0.1 - - [18/Apr/2019 20:14:17] "{"text":-1220615319}POST / HTTP/1.1" 405 -
127.0.0.1 - - [18/Apr/2019 20:14:18] "{"text":-1429538713}POST / HTTP/1.1" 405 -
127.0.0.1 - - [18/Apr/2019 20:14:19] "{"text":118249332}POST / HTTP/1.1" 405 -
127.0.0.1 - - [18/Apr/2019 20:14:19] "{"text":-951589224}POST / HTTP/1.1" 405 -

for this log, first request is success, but others failed. It does not seem to clear the last request content.

if i remove this code:

BaseHTTPRequestHandler.protocol_version = "HTTP/1.1"

it's ok again.

Has anyone encountered the same problem? i used flask version : 1.0.2


update: i know what happened, i need to read the request contents:

@app.route('/', methods=['POST'])
def hello_world():
    # read the request content
    print(request.json)
    print("\n")
    resp = make_response("{'123':'aaa'}")
    return resp

thanks all.

star
  • 321
  • 2
  • 9
  • Does this answer your question? [How to make Flask/ keep Ajax HTTP connection alive?](https://stackoverflow.com/questions/10523879/how-to-make-flask-keep-ajax-http-connection-alive) – Rene B. Nov 20 '19 at 13:06

1 Answers1

1

Instead of using BaseHTTPRequestHandler, you can employ the default request_handler WSGIRequestHandler.

Since WSGIRequestHandler extends BaseHTTPRequestHandler, you can specify the HTTP protocol version you want to use. If you set the property to HTTP/1.1, the connection will stay alive.

from flask import Flask, make_response, Response
from werkzeug.serving import WSGIRequestHandler
from flask import jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    resp = make_response("{'123':'aaa'}")
    return resp

if __name__ == '__main__':
    WSGIRequestHandler.protocol_version = "HTTP/1.1"
    app.run()

Don't forget to include from werkzeug.serving import WSGIRequestHandler

Gabe
  • 956
  • 7
  • 8