File size: 3,004 Bytes
9c36111
ec61139
0d2544a
 
 
 
9c36111
 
 
0d2544a
 
 
6e1ef2b
 
 
c8aef77
 
 
 
0d2544a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c36111
0d2544a
 
 
8f0b65d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from typing import List
from fastapi import FastAPI, HTTPException, Request
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, request: Request):
    body = await request.body()
    print("RAW BODY RECEIVED →", body.decode())
    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")


@app.get("/files/{origin_id}")
async def get_file_by_origin_id(origin_id: int):
    try:
        for filename in os.listdir(BASE_DIR):
            if filename.startswith(f"{origin_id}_") and filename.endswith(".json"):
                filepath = os.path.join(BASE_DIR, filename)
                if os.path.isfile(filepath):
                    try:
                        with open(filepath, "r") as f:
                            file_content = f.read()
                            try:
                                file_content_json = json.loads(file_content)
                                return JSONResponse({"filename": filename, "content": file_content_json})
                            except json.JSONDecodeError:
                                return JSONResponse({"filename": filename, "content": file_content})
                    except (IOError, OSError) as e:
                        raise HTTPException(status_code=500, detail=f"Erro ao ler o ficheiro {filename}: {e}")
        raise HTTPException(status_code=404, detail=f"Ficheiro com originId '{origin_id}' não encontrado")
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail="Diretório de dados não encontrado")