37 lines
872 B
Python
37 lines
872 B
Python
"""Helpers para subidas temporales desde la app desktop."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import tempfile
|
|
from contextlib import contextmanager
|
|
from typing import Iterator
|
|
|
|
from fastapi import UploadFile
|
|
|
|
|
|
@contextmanager
|
|
def temp_upload_path(upload: UploadFile, *, suffix: str | None = None) -> Iterator[str]:
|
|
"""Guarda un UploadFile en disco temporal y lo elimina al salir."""
|
|
ext = suffix
|
|
if ext is None and upload.filename:
|
|
_, ext = os.path.splitext(upload.filename)
|
|
if not ext:
|
|
ext = ".bin"
|
|
|
|
fd, path = tempfile.mkstemp(suffix=ext)
|
|
os.close(fd)
|
|
try:
|
|
upload.file.seek(0)
|
|
with open(path, "wb") as handle:
|
|
while True:
|
|
chunk = upload.file.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
handle.write(chunk)
|
|
yield path
|
|
finally:
|
|
try:
|
|
os.unlink(path)
|
|
except OSError:
|
|
pass
|