python - 烧瓶保持活动连接请求失败
问题描述
我想创建 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
谢谢大家。
解决方案
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
推荐阅读
- sql - Postgres 查询显示可为空的字段
- php - 如何使用 cURL 或 PHP 获取 cookie 特定值
- javascript - Select2 删除选项在 jquery 中不起作用
- c++ - Embarcadero C++ builder 10.4.2-附加到进程在 64 位上不起作用
- android - 如何在顶部构建具有比例的自定义搜索栏
- javascript - Gatsby GraphQL 一次下载多个图像
- android - 如何在 RXjava - Android 中为完整的观察者设置 TimeOut?
- html - 尝试查找 URL 的创建日期
- javascript - 在 vue 中打印发票(账单)只是文本
- amazon-web-services - AWS STS 在 docker 容器中承担角色“无法找到凭证”