From a2a96282de7e588b2df01b32984a97dc0a77820b Mon Sep 17 00:00:00 2001 From: chaos Date: Wed, 8 Jul 2026 13:21:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=90=AF=E7=94=A8=E5=93=8D=E5=BA=94?= =?UTF-8?q?=E5=8E=8B=E7=BC=A9(gzip/brotli/zstd)=20+=20=E4=BC=98=E5=8C=96SS?= =?UTF-8?q?E=E6=B5=81=E5=BC=8Fchunk=5Fsize?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 flask-compress 中间件,长文本响应自动压缩(压缩率70-80%) - 压缩阈值设为256字节,小响应不压缩 - SSE流式 chunk_size 从 4096 提升到 16384,减少分片开销 - 压缩白名单包含 text/event-stream,SSE也支持压缩 - 解决长文本响应体积过大导致超时/内存溢出的问题 --- ai/huawei_gateway.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ai/huawei_gateway.py b/ai/huawei_gateway.py index 2cd5526..3cb7005 100755 --- a/ai/huawei_gateway.py +++ b/ai/huawei_gateway.py @@ -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: