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: