首页 > 解决方案 > 烧瓶保持活动连接请求失败

问题描述

我想创建 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()

我发送了一些请求:

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

我收到了一些错误:

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 -

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

如果我删除此代码:

BaseHTTPRequestHandler.protocol_version = "HTTP/1.1"

又好了。

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


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

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

谢谢大家。

标签: pythonflask

解决方案


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()

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


推荐阅读