From 92dedc38e73a17098eae8f0115a7259413862595 Mon Sep 17 00:00:00 2001 From: zzy <3146527494@qq.com> Date: Fri, 13 Nov 2026 03:07:04 +0800 Subject: [PATCH] =?UTF-8?q?fix(upload):=20=E5=A4=A7=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E6=B5=81=E5=BC=8F=E8=90=BD=E7=9B=98=20+=20gu?= =?UTF-8?q?nicorn=20=E7=94=9F=E4=BA=A7=E5=90=AF=E5=8A=A8=20+=20=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E4=BD=93=E4=B8=8A=E9=99=90=E5=BF=AB=E9=80=9F=E6=8B=92?= =?UTF-8?q?=E7=BB=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 400MB 级上传时 file.read() 会让单请求常驻数百 MB 内存,并把「传完->响应」的 间隔拉长到客户端读超时,表现为 499 Client Closed Request。改为按 1MB 分块 写入 .part 后 fsync + 原子改名;同时用 gunicorn(gthread, 单 worker 多线程, 避免 APScheduler 重复执行) 承担生产流量,超时放宽到 1 小时。 --- Dockerfile | 2 +- database.py | 76 +++++++++++++++++++++++++++++++++++++++++++ gunicorn.conf.py | 34 +++++++++++++++++++ requirements.txt | 1 + routes/submissions.py | 24 ++++++++++---- wsgi.py | 9 +++++ 6 files changed, 139 insertions(+), 7 deletions(-) create mode 100644 gunicorn.conf.py create mode 100644 wsgi.py diff --git a/Dockerfile b/Dockerfile index f72da8b..13c860b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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"] diff --git a/database.py b/database.py index bc7502e..1c4e0c4 100644 --- a/database.py +++ b/database.py @@ -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: diff --git a/gunicorn.conf.py b/gunicorn.conf.py new file mode 100644 index 0000000..28b2464 --- /dev/null +++ b/gunicorn.conf.py @@ -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 = "*" diff --git a/requirements.txt b/requirements.txt index 92e0684..f4b679f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,3 +10,4 @@ PyYAML>=6.0 pymysql>=1.1.0 requests>=2.31.0 pillow>=10.0.0 +gunicorn>=21.2.0 diff --git a/routes/submissions.py b/routes/submissions.py index 671c270..5997c25 100644 --- a/routes/submissions.py +++ b/routes/submissions.py @@ -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 diff --git a/wsgi.py b/wsgi.py new file mode 100644 index 0000000..143293d --- /dev/null +++ b/wsgi.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +"""WSGI 入口(gunicorn 使用)。 + +app.py 在导入时已完成:建表/迁移、蓝图注册、调度器启动。这里只把它暴露成 +模块级 `app`,不要再重复初始化。本地调试仍可用 `python app.py`。 +""" +from app import app # noqa: F401 + +__all__ = ["app"]