fix(): Ajuste para criar de forma dinâmica nomes de arquivos que não foram informados
This commit is contained in:
parent
0b36096fcc
commit
4fd095aa93
1 changed files with 34 additions and 2 deletions
|
|
@ -15,6 +15,9 @@ from packages.v1.administrativo.schemas.ato_principal_schema import (
|
|||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
import datetime
|
||||
import mimetypes
|
||||
|
||||
|
||||
# Configuração da Chave AES
|
||||
|
|
@ -31,6 +34,23 @@ GROUP_SIZE = int(
|
|||
UPLOAD_DIR = Path(os.environ.get("STORAGE", "./storage"))
|
||||
|
||||
|
||||
# Função utilitária para detectar tipo MIME e extensão de um base64
|
||||
def _get_file_extension_from_base64(base64_content: str) -> str:
|
||||
try:
|
||||
header, _ = (
|
||||
base64_content.split(",", 1)
|
||||
if "," in base64_content
|
||||
else ("", base64_content)
|
||||
)
|
||||
if "data:" in header and ";" in header:
|
||||
mime_type = header.split("data:")[1].split(";")[0]
|
||||
ext = mimetypes.guess_extension(mime_type)
|
||||
return ext or ".bin"
|
||||
except Exception:
|
||||
pass
|
||||
return ".bin" # fallback
|
||||
|
||||
|
||||
# Salva o arquivo Base64 em disco e retorna o caminho completo
|
||||
def _save_file_from_base64(base64_content: str, file_name: str, ato_id: int) -> str:
|
||||
"""
|
||||
|
|
@ -177,8 +197,20 @@ class SaveMultipleRepository:
|
|||
base64_content = getattr(doc, "arquivo", None)
|
||||
file_url_path = None
|
||||
|
||||
if base64_content and doc.nome_documento:
|
||||
file_name = doc.nome_documento
|
||||
if base64_content:
|
||||
|
||||
# Se o nome do documento veio vazio, cria um nome dinâmico
|
||||
if not doc.nome_documento:
|
||||
# Detecta a extensão a partir do base64, se possível
|
||||
file_ext = _get_file_extension_from_base64(base64_content)
|
||||
|
||||
# Cria um nome único com timestamp e UUID
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
unique_id = uuid.uuid4().hex[:8] # reduzido para ficar mais limpo
|
||||
file_name = f"documento_{timestamp}_{unique_id}{file_ext}"
|
||||
else:
|
||||
file_name = doc.nome_documento
|
||||
|
||||
file_url_path = _save_file_from_base64(
|
||||
base64_content, file_name, new_ato_id
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue