чанки 10KB base64: /chunk_json + uploadFileChunked10k, v1.33

This commit is contained in:
2026-06-17 21:52:50 +04:00
parent f0c3d93599
commit 637fdce1bc
2 changed files with 121 additions and 53 deletions
+80 -2
View File
@@ -77,7 +77,7 @@ class ContractsApp:
def _add_routes(self):
self.app.add_url_rule("/", "index", self._index, methods=["GET", "POST"])
self.app.add_url_rule("/parse/<cid>", "parse", self._parse, methods=["GET"])
self.app.add_url_rule("/chunk", "chunk", self._chunk_upload, methods=["POST"])
self.app.add_url_rule("/chunk_json", "chunk_json", self._chunk_json, methods=["POST"])
self.app.add_url_rule("/upload", "upload_json", self._upload_json, methods=["POST"])
self.app.add_url_rule("/health", "health", self._health)
self.app.register_blueprint(test_bp)
@@ -203,7 +203,85 @@ class ContractsApp:
_log("upload_outer_error", str(e))
return jsonify({"error": f"Крах: {e}"}), 500
# ── Чанковая загрузка ──────────────────────────────────────
# ── Чанковая загрузка base64 (10KB) ───────────────────────
def _chunk_json(self):
"""Принять чанк base64. На последнем — собрать и сохранить."""
data = request.get_json(silent=True) or {}
upload_id = data.get("upload_id", "")
filename = data.get("filename", "")
chunk_index = data.get("chunk_index", 0)
total_chunks = data.get("total_chunks", 1)
b64_piece = data.get("data", "")
cid = data.get("cid")
if not upload_id or not b64_piece:
return jsonify({"error": "Нет upload_id или data"}), 400
# Храним в той же таблице chunks (chunk_data = base64 кусок как текст)
db.execute(
"INSERT INTO chunks (upload_id, chunk_index, chunk_data, filename, mime, total_chunks, cid) "
"VALUES (%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (upload_id, chunk_index) DO NOTHING",
(upload_id, chunk_index, b64_piece.encode(), filename, "", total_chunks, cid),
)
count_res, _ = db.query("SELECT COUNT(*) FROM chunks WHERE upload_id=%s", (upload_id,))
received = count_res["rows"][0][0] if count_res else 0
if received == total_chunks:
try:
rows_res, _ = db.query(
"SELECT chunk_data FROM chunks WHERE upload_id=%s ORDER BY chunk_index",
(upload_id,),
)
full_b64 = b"".join(r[0] for r in rows_res["rows"]).decode()
# Получить метаданные
meta, _ = db.query_one("SELECT filename, cid FROM chunks WHERE upload_id=%s LIMIT 1", (upload_id,))
fname = meta["filename"] if meta else filename
fcid = meta["cid"] if meta else cid
conn, err = db.connect()
if err:
return jsonify({"error": f"БД: {err}"}), 500
try:
cur = conn.cursor()
if fcid:
contract_id = fcid
else:
cur.execute(
"INSERT INTO contracts (number, client) VALUES (%s, %s) RETURNING id",
("б" + __import__("datetime").datetime.now().strftime("%Y%m%d-%H%M"), ""),
)
contract_id = cur.fetchone()[0]
mime = mimeutil.guess_mime(fname) or "application/octet-stream"
cur.execute(
"INSERT INTO documents (filename, mime_type, original_b64, status) VALUES (%s,%s,%s,'uploaded')",
(fname, mime, full_b64),
)
cur.execute("SELECT id FROM documents WHERE filename=%s AND status='uploaded' ORDER BY created_at DESC LIMIT 1", (fname,))
row = cur.fetchone()
doc_id = row[0] if row else None
if doc_id:
cur.execute(
"INSERT INTO supplements (contract_id, document_id, type) VALUES (%s,%s,'initial')",
(str(contract_id), str(doc_id)),
)
conn.commit()
cur.close()
finally:
db.put_conn(conn)
except Exception as e:
return jsonify({"error": f"Сборка: {e}"}), 500
finally:
db.execute("DELETE FROM chunks WHERE upload_id=%s", (upload_id,))
return jsonify({"contract_id": str(contract_id)})
return jsonify({"chunk": chunk_index, "received": received, "total": total_chunks})
# ── Старая чанковая загрузка ───────────────────────────────
def _chunk_upload(self):
"""Принять чанк. Хранить в БД. На последнем — собрать и сохранить."""