ERP/server/app_optimized.py
2026-01-03 19:18:40 +08:00

107 lines
3.5 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
优化的Flask应用启动脚本
启用Keep-Alive、缓存和gzip压缩
"""
from app import app
from flask import after_this_request, request
import gzip
from io import BytesIO
import os
# 启用Keep-Alive
class KeepAliveMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
def new_start_response(status, response_headers, exc_info=None):
# 添加Keep-Alive头
response_headers.append(('Connection', 'keep-alive'))
response_headers.append(('Keep-Alive', 'timeout=5, max=100'))
return start_response(status, response_headers, exc_info)
return self.app(environ, new_start_response)
# 启用Gzip压缩
class GzipMiddleware:
def __init__(self, app, minimum_size=500):
self.app = app
self.minimum_size = minimum_size
def __call__(self, environ, start_response):
def new_start_response(status, response_headers, exc_info=None):
self.start_response = start_response
self.response_headers = response_headers
return start_response(status, response_headers, exc_info)
app_iter = self.app(environ, new_start_response)
try:
# 检查是否支持gzip
accept_encoding = environ.get('HTTP_ACCEPT_ENCODING', '')
if 'gzip' not in accept_encoding:
return app_iter
# 收集响应数据
response_data = b''.join(app_iter)
# 只压缩大于minimum_size的响应
if len(response_data) < self.minimum_size:
return [response_data]
# 压缩数据
buffer = BytesIO()
with gzip.GzipFile(mode='wb', fileobj=buffer) as gz:
gz.write(response_data)
gzipped_data = buffer.getvalue()
# 修改响应头
for header, value in self.response_headers:
if header.lower() == 'content-length':
self.response_headers.remove([header, value])
break
self.response_headers.append(('Content-Encoding', 'gzip'))
self.response_headers.append(('Content-Length', str(len(gzipped_data))))
# 发送响应
self.start_response(status, self.response_headers, exc_info)
return [gzipped_data]
except Exception as e:
# 出错时返回原始响应
return app_iter
# 添加缓存头
@app.after_request
def add_cache_headers(response):
# 静态资源缓存1小时
if request.path.startswith('/assets/') or request.path.startswith('/js/') or request.path.startswith('/css/'):
response.cache_control.max_age = 3600
response.headers['Cache-Control'] = 'public, max-age=3600'
# API不缓存
elif request.path.startswith('/api/'):
response.headers['Cache-Control'] = 'no-cache'
return response
# 应用中间件
app.wsgi_app = KeepAliveMiddleware(app.wsgi_app)
app.wsgi_app = GzipMiddleware(app.wsgi_app)
if __name__ == '__main__':
print("🚀 启动优化版服务器...")
print("✅ Keep-Alive: 已启用")
print("✅ Gzip压缩: 已启用")
print("✅ 静态资源缓存: 1小时")
# 使用多线程模式
app.run(
host='0.0.0.0',
port=int(os.environ.get('PORT', '5000')),
threaded=True,
debug=False
)