fix(upload): 大文件改为流式落盘 + gunicorn 生产启动 + 请求体上限快速拒绝
400MB 级上传时 file.read() 会让单请求常驻数百 MB 内存,并把「传完->响应」的 间隔拉长到客户端读超时,表现为 499 Client Closed Request。改为按 1MB 分块 写入 .part 后 fsync + 原子改名;同时用 gunicorn(gthread, 单 worker 多线程, 避免 APScheduler 重复执行) 承担生产流量,超时放宽到 1 小时。
This commit is contained in:
+76
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user