from typing import List from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse import os import json from models import RequestModel app = FastAPI() BASE_DIR = "/tmp/data" @app.post("/save") async def save(image_data: RequestModel): os.makedirs(BASE_DIR, exist_ok=True) filename = os.path.join(BASE_DIR, f"{image_data.originId}_{image_data.assetCode}.json") with open(filename, "w") as f: json.dump(image_data.dict(), f, indent=4) return True @app.get("/files") async def list_files(): try: files_data = [] for filename in os.listdir(BASE_DIR): filepath = os.path.join(BASE_DIR, filename) if os.path.isfile(filepath): try: with open(filepath, "r") as f: file_content = f.read() # Lê o conteúdo do ficheiro # Tenta decodificar o conteúdo como JSON, se possível try: file_content_json = json.loads(file_content) files_data.append({"filename": filename, "content": file_content_json}) except json.JSONDecodeError: files_data.append({"filename": filename, "content": file_content}) # Se não for JSON, retorna o texto except (IOError, OSError) as e: raise HTTPException(status_code=500, detail=f"Erro ao ler o ficheiro {filename}: {e}") return JSONResponse({"files_data": files_data}) except FileNotFoundError: raise HTTPException(status_code=404, detail="Diretório de dados não encontrado")