fix(upload): 大文件改为流式落盘 + gunicorn 生产启动 + 请求体上限快速拒绝

400MB 级上传时 file.read() 会让单请求常驻数百 MB 内存,并把「传完->响应」的
间隔拉长到客户端读超时,表现为 499 Client Closed Request。改为按 1MB 分块
写入 .part 后 fsync + 原子改名;同时用 gunicorn(gthread, 单 worker 多线程,
避免 APScheduler 重复执行) 承担生产流量,超时放宽到 1 小时。
This commit is contained in:
zzy
2026-11-13 03:07:04 +08:00
parent 0a23742170
commit 92dedc38e7
6 changed files with 139 additions and 7 deletions
+1 -1
View File
@@ -22,4 +22,4 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8080
CMD ["python", "app.py"]
CMD ["gunicorn", "--config", "gunicorn.conf.py", "wsgi:app"]
+76
View File
@@ -1185,6 +1185,82 @@ def save_file(form_id, file_data, filename, original_name=None, mime_type=None,
return file_id
def save_file_stream(form_id, file_storage, filename, original_name=None, mime_type=None,
field_name=None, submission_id=None, chunk_size=1024 * 1024):
"""流式把上传文件写到磁盘,全程不把整个文件读进内存。
400MB 级文件用 file.read() 会让单个请求常驻 400MB 内存,同时把「客户端传完 →
服务端响应」的间隔拉长到客户端读超时(表现就是 499 Client Closed Request)。
这里按块搬运:先写 .part 临时文件,fsync 后原子改名,失败则清理行与残留文件。
Returns:
file_id: 文件记录ID
"""
stream = file_storage.stream
# 取大小:FileStorage.stream 是落过盘的临时文件,seek 到末尾是 O(1)
size = 0
try:
stream.seek(0, os.SEEK_END)
size = stream.tell()
stream.seek(0)
except (OSError, AttributeError, ValueError):
size = int(file_storage.content_length or 0)
try:
stream.seek(0)
except (OSError, AttributeError, ValueError):
pass
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO files "
"(form_id, submission_id, filename, original_name, file_size, mime_type, "
" file_data, uploaded_at, field_name) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
form_id,
submission_id,
filename,
original_name,
size,
mime_type,
b"", # 内容在磁盘;字段保留 NOT NULL 约束,置 0 字节占位
datetime.now().isoformat(),
field_name,
),
)
file_id = cursor.lastrowid
rel_path = f"{form_id}/{file_id}.bin"
abs_path = _disk_path(rel_path)
part_path = abs_path + ".part"
written = 0
try:
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
with open(part_path, "wb") as out:
while True:
chunk = stream.read(chunk_size)
if not chunk:
break
out.write(chunk)
written += len(chunk)
out.flush()
os.fsync(out.fileno())
os.replace(part_path, abs_path)
except BaseException:
for path in (part_path, abs_path):
try:
os.remove(path)
except OSError:
pass
cursor.execute("DELETE FROM files WHERE id = ?", (file_id,))
raise
cursor.execute("UPDATE files SET file_path = ?, file_size = ? WHERE id = ?",
(rel_path, written, file_id))
return file_id
def get_file(file_id):
"""获取单个文件(file_data 从磁盘读取)"""
with get_db_connection() as conn:
+34
View File
@@ -0,0 +1,34 @@
# -*- coding: utf-8 -*-
"""gunicorn 生产配置。
为什么不是多 worker:app.py 在模块级启动 APScheduler(清理/指标任务),多进程会
让同一批定时任务在每个 worker 里各跑一遍。这里用「单 worker + 多线程」,既保证
定时任务只跑一次,又让并发上传互不阻塞(上传是 I/O 密集,GIL 在 read/write 时释放)。
超时给到 1 小时:400MB 在移动网络下光传输就可能十几分钟,之后的落盘也不能被打断。
"""
import os
bind = "0.0.0.0:8080"
workers = 1
worker_class = "gthread"
threads = int(os.environ.get("UPLOAD_THREADS", "16"))
timeout = int(os.environ.get("UPLOAD_TIMEOUT", "3600"))
graceful_timeout = 120
keepalive = 75
# worker 心跳放 tmpfs,避免和附件写盘抢 IO
worker_tmp_dir = "/dev/shm"
limit_request_line = 0
limit_request_field_size = 0
limit_request_fields = 200
accesslog = "-"
errorlog = "-"
loglevel = os.environ.get("UPLOAD_LOG_LEVEL", "info")
access_log_format = '%(h)s "%(r)s" %(s)s %(b)s %(L)s "%(a)s"'
forwarded_allow_ips = "*"
+1
View File
@@ -10,3 +10,4 @@ PyYAML>=6.0
pymysql>=1.1.0
requests>=2.31.0
pillow>=10.0.0
gunicorn>=21.2.0
+18 -6
View File
@@ -119,10 +119,23 @@ def check_submission():
return jsonify(exists=tail in submitted_students)
# 请求体硬上限(字节)。表单自己的 maxSize 只能等 multipart 解析完才知道,
# 这里按 Content-Length 先拦一道:超限直接 413,不接整包,客户端立刻失败而不是
# 传几十分钟后被拦。默认 1GB,可用环境变量调整。
MAX_REQUEST_BYTES = int(os.environ.get("UPLOAD_MAX_REQUEST_BYTES", str(1024 ** 3)))
@bp.route('/api/submit', methods=['POST'])
def submit_form():
"""通用表单提交接口 - BLOB存储版本"""
"""通用表单提交接口 - 磁盘存储版本(大文件流式落盘)"""
try:
declared = request.content_length or 0
if declared and declared > MAX_REQUEST_BYTES:
return jsonify(
success=False,
message=f"请求体过大({declared / 1048576:.0f}MB),上限 {MAX_REQUEST_BYTES // 1048576}MB",
), 413
form_id = request.form.get('formId', 'default')
tail = request.form.get('studentId', '').strip()
@@ -283,7 +296,7 @@ def submit_form():
)
# 处理文件上传 - 存储为BLOB
from database import save_file
from database import save_file, save_file_stream
for field in form['fields']:
if field['type'] == 'file':
file = request.files.get(field['name'])
@@ -314,12 +327,11 @@ def submit_form():
else:
filename = f"{base_name}.{ext}"
file_data = file.read()
mime_type = file.content_type or 'application/octet-stream'
file_id = save_file(
file_id = save_file_stream(
form_id=form_id,
file_data=file_data,
file_storage=file,
filename=filename,
original_name=file.filename,
mime_type=mime_type,
@@ -329,7 +341,7 @@ def submit_form():
new_file_ids.append(file_id)
uploaded_files.append(filename)
try:
insert_business_metric('files_uploaded', len(file_data))
insert_business_metric('files_uploaded', size)
except Exception:
pass
+9
View File
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
"""WSGI 入口(gunicorn 使用)。
app.py 在导入时已完成:建表/迁移、蓝图注册、调度器启动。这里只把它暴露成
模块级 `app`,不要再重复初始化。本地调试仍可用 `python app.py`。
"""
from app import app # noqa: F401
__all__ = ["app"]