Flask 保持活动连接请求失败

sta*_*tar 5 python flask

我想创建 Keep-Alive http 连接,但失败了。

我构建了一个演示应用程序。

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()
Run Code Online (Sandbox Code Playgroud)

我发送一些请求:

{"text":-1193959466}
{"text":-1139614796}
{"text":837415749}
{"text":-1220615319}
{"text":-1429538713}
{"text":118249332}
{"text":-951589224}
Run Code Online (Sandbox Code Playgroud)

我收到一些错误:

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 -
Run Code Online (Sandbox Code Playgroud)

对于此日志,第一个请求成功,但其他请求失败。似乎没有清除最后一个请求内容。

如果我删除此代码:

BaseHTTPRequestHandler.protocol_version = "HTTP/1.1"
Run Code Online (Sandbox Code Playgroud)

又好了。

有人遇到过同样的问题吗?我使用烧瓶版本:1.0.2


更新:我知道发生了什么,我需要阅读请求内容:

{"text":-1193959466}
{"text":-1139614796}
{"text":837415749}
{"text":-1220615319}
{"text":-1429538713}
{"text":118249332}
{"text":-951589224}
Run Code Online (Sandbox Code Playgroud)

谢谢大家。

Gab*_* H. 1

BaseHTTPRequestHandler您可以使用默认的 request_handler来代替使用WSGIRequestHandler

由于WSGIRequestHandler扩展了BaseHTTPRequestHandler,因此您可以指定要使用的 HTTP 协议版本。如果将该属性设置为HTTP/1.1,连接将保持活动状态。

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()
Run Code Online (Sandbox Code Playgroud)

不要忘记包括from werkzeug.serving import WSGIRequestHandler