corrigindo upload
This commit is contained in:
1 parent
73693e5da9
commit
d2a68fa744
9 files changed
+4295
-74
No files matched your search
@@ -7,6 +7,7 @@ import shutil
|
||||
import time
|
||||
import io
|
||||
import threading
|
||||
from threading import Lock
|
||||
|
||||
from flask import Flask, request, jsonify, send_file, redirect
|
||||
from flask_cors import CORS
|
||||
@@ -41,6 +42,15 @@ from utils import (
|
||||
SAMPLE_MANIFEST,
|
||||
)
|
||||
|
||||
import logging
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO
|
||||
) # obriga o servidor a mostrar os sucessos também
|
||||
|
||||
# Trava do build do Jekyll
|
||||
JEKYLL_LOCK = Lock()
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# --- CONFIGURAÇÃO DE SEGURANÇA E BANCO ---
|
||||
@@ -164,17 +174,13 @@ def allowed_sample(filename):
|
||||
and filename.rsplit(".", 1)[1].lower() in ALLOWED_SAMPLE_EXTENSIONS
|
||||
)
|
||||
|
||||
|
||||
def run_jekyll_build():
|
||||
RUBY_BIN_PATH = "/usr/bin/ruby3.2"
|
||||
BUNDLE_PATH = (
|
||||
"/nethome/jotachina/projetos/mmpSearch/vendor/bundle/ruby/3.2.0/bin/bundle"
|
||||
)
|
||||
# Prepara o ambiente para o subprocesso
|
||||
BUNDLE_PATH = "/nethome/jotachina/projetos/mmpSearch/vendor/bundle/ruby/3.2.0/bin/bundle"
|
||||
|
||||
env_vars = os.environ.copy()
|
||||
# Adiciona o caminho do Ruby ao PATH do usuário www-data temporariamente
|
||||
env_vars["PATH"] = f"{RUBY_BIN_PATH}:{env_vars.get('PATH', '')}"
|
||||
print("Iniciando build do Jekyll...")
|
||||
|
||||
command = [
|
||||
BUNDLE_PATH,
|
||||
"exec",
|
||||
@@ -183,18 +189,24 @@ def run_jekyll_build():
|
||||
"--destination",
|
||||
"/var/www/html/trens/mmpSearch/",
|
||||
]
|
||||
try:
|
||||
# Redirecionamos a saída para DEVNULL para não encher o buffer e travar
|
||||
subprocess.Popen(
|
||||
command,
|
||||
cwd=BASE_DATA,
|
||||
env=env_vars,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
print("Jekyll Build iniciado em segundo plano (background).")
|
||||
except Exception as e:
|
||||
print(f"Erro ao iniciar Jekyll: {e}")
|
||||
|
||||
logging.info("⏳ Aguardando liberação para iniciar build do Jekyll...")
|
||||
with JEKYLL_LOCK:
|
||||
logging.info("🔨 Iniciando build do Jekyll (Travando a fila)...")
|
||||
try:
|
||||
resultado = subprocess.run(
|
||||
command,
|
||||
cwd=BASE_DATA,
|
||||
env=env_vars,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
logging.info("✅ Jekyll Build concluído com sucesso!")
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.error(f"❌ ERRO FATAL no Jekyll Build (Code {e.returncode}):\n{e.stderr}")
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Erro inesperado ao chamar Jekyll: {e}")
|
||||
|
||||
|
||||
def load_manifest_keys():
|
||||
@@ -321,31 +333,27 @@ def update_xml_paths_exact(mmp_filename, replacements):
|
||||
|
||||
|
||||
def run_heavy_tasks_in_background():
|
||||
"""Esta função roda isolada sem travar o usuário"""
|
||||
print("--- [BACKGROUND] Iniciando reconstrução de índices ---")
|
||||
logging.info("--- [BACKGROUND] Iniciando tarefas assíncronas ---")
|
||||
try:
|
||||
|
||||
# 2. Isso gera os manifestos (Python puro)
|
||||
generate_manifests(SRC_MMPSEARCH)
|
||||
|
||||
# 3. Isso chama o subprocesso do Jekyll (Externo)
|
||||
# Mantém sua função original que usa subprocess
|
||||
run_jekyll_build()
|
||||
|
||||
print("--- [BACKGROUND] Tarefas concluídas com sucesso ---")
|
||||
logging.info("--- [BACKGROUND] Todas as tarefas concluídas ---")
|
||||
except Exception as e:
|
||||
print(f"--- [BACKGROUND] Erro: {e} ---")
|
||||
|
||||
logging.error(f"--- [BACKGROUND] Erro: {e} ---")
|
||||
|
||||
def process_and_build(filename):
|
||||
"""Função chamada pela rota de upload"""
|
||||
# Processamento inicial do arquivo (rápido)
|
||||
result = process_single_file(filename)
|
||||
|
||||
# 1. Preparamos os 3 dados que o main.py exige: (file_name, clean_slug, total_files)
|
||||
name_without_ext = os.path.splitext(filename)[0]
|
||||
clean_slug = slugify(name_without_ext)
|
||||
args_tuple = (filename, clean_slug, 1) # O 1 representa que é só 1 arquivo no total
|
||||
|
||||
# 2. Passamos a tupla!
|
||||
result = process_single_file(args_tuple)
|
||||
|
||||
if result["success"]:
|
||||
# Em vez de chamar rebuild_indexes() direto, criamos a Thread
|
||||
# O Flask vai responder o return abaixo imediatamente,
|
||||
# enquanto a thread continua rodando no servidor.
|
||||
task_thread = threading.Thread(target=run_heavy_tasks_in_background)
|
||||
task_thread.start()
|
||||
|
||||
|
||||
Reference in new issue
Block a user