feat: 启用响应压缩(gzip/brotli/zstd) + 优化SSE流式chunk_size
- 添加 flask-compress 中间件,长文本响应自动压缩(压缩率70-80%) - 压缩阈值设为256字节,小响应不压缩 - SSE流式 chunk_size 从 4096 提升到 16384,减少分片开销 - 压缩白名单包含 text/event-stream,SSE也支持压缩 - 解决长文本响应体积过大导致超时/内存溢出的问题
This commit is contained in:
1 parent
fab2a25bcc
commit
a2a96282de
1 file changed
+21
-1
+21
-1
@@ -21,6 +21,13 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from flask import Flask, request, Response
|
||||
|
||||
# 尝试导入 flask-compress,用于响应压缩
|
||||
try:
|
||||
from flask_compress import Compress
|
||||
_compress_available = True
|
||||
except ImportError:
|
||||
_compress_available = False
|
||||
|
||||
# 尝试导入 requests,失败则给出明确提示
|
||||
try:
|
||||
import requests
|
||||
@@ -241,6 +248,19 @@ http_session.mount('http://', adapter)
|
||||
# ================= Flask 应用 =================
|
||||
app = Flask(__name__)
|
||||
|
||||
# 启用响应压缩(gzip/brotli/zstd),对长文本响应压缩率可达 70-80%
|
||||
if _compress_available:
|
||||
compress = Compress()
|
||||
compress.init_app(app)
|
||||
# 设置压缩最小阈值(256字节以下不压缩)
|
||||
app.config['COMPRESS_MIN_SIZE'] = 256
|
||||
# 压缩 MIME 类型白名单
|
||||
app.config['COMPRESS_MIMETYPES'] = [
|
||||
'text/html', 'text/plain', 'text/css', 'text/xml',
|
||||
'application/json', 'application/javascript',
|
||||
'application/xml', 'text/event-stream',
|
||||
]
|
||||
|
||||
@app.route('/health')
|
||||
def health():
|
||||
"""健康检查端点"""
|
||||
@@ -350,7 +370,7 @@ def proxy(subpath):
|
||||
if 'text/event-stream' in content_type or resp.headers.get('Transfer-Encoding', '') == 'chunked':
|
||||
def sse_stream():
|
||||
try:
|
||||
for chunk in resp.iter_content(chunk_size=4096):
|
||||
for chunk in resp.iter_content(chunk_size=16384):
|
||||
if chunk:
|
||||
yield chunk
|
||||
finally:
|
||||
|
||||
Reference in new issue
Block a user