From 1a8e2eb91ec1e3a0c7e4d2d1dc7b01191ca33654 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Gon=C3=A7alves?= Date: Fri, 27 Sep 2024 11:20:45 +0200 Subject: [PATCH] Reformat return from `/unit` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * This still needs refactoring, pushing it just for the hackathon. Signed-off-by: João Gonçalves --- units/concepts.py | 31 +++++++++++++++++++++++++------ units/main.py | 1 - units/routes.py | 4 ++-- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/units/concepts.py b/units/concepts.py index 49b4d6e..5066bb4 100644 --- a/units/concepts.py +++ b/units/concepts.py @@ -1,8 +1,10 @@ from functools import partial from itertools import groupby +from typing import Optional -import structlog import httpx +import structlog +from pydantic import BaseModel from units.settings import get_settings @@ -112,10 +114,27 @@ def get_all_data_for_qk_iri( lang_checker = partial(language_filter, lang=lang.lower() if lang else None) return { - key: [ - reformat_predicate_object(obj, remove_namespaces=remove_namespaces) - for obj in group - if lang_checker(obj["o"]) - ] + key: { + ( + remove_graph_namespaces(obj_key) if remove_namespaces else obj_key + ): format_objects(obj, lang) + for obj_key, obj in groupby(group, key=lambda x: x["p"]["value"]) + } for key, group in groupby(results, key=lambda x: x["s"]["value"]) } + + +def format_objects(obj, lang: Optional[str] = None): + l = list( + map( + lambda x: x["o"]["value"], + filter( + lambda x: "xml:lang" not in x["o"] or language_filter(x["o"], lang), + obj, + ), + ) + ) + if len(l) == 0: + return None + return l if len(l) > 1 else l[0] + diff --git a/units/main.py b/units/main.py index fc2d5e9..3e09564 100644 --- a/units/main.py +++ b/units/main.py @@ -6,7 +6,6 @@ import uvicorn from fastapi import FastAPI from fastapi_versioning import VersionedFastAPI - from starlette.middleware.cors import CORSMiddleware from units.routes import router diff --git a/units/routes.py b/units/routes.py index 7bd90b0..94c62af 100644 --- a/units/routes.py +++ b/units/routes.py @@ -1,9 +1,9 @@ -from fastapi import APIRouter, Depends, Request, HTTPException +from fastapi import APIRouter, Depends, HTTPException, Request from fastapi.responses import JSONResponse from fastapi_versioning import version +from units.concepts import get_all_data_for_qk_iri, get_qk_for_iri from units.schema import VersionResponse -from units.concepts import get_qk_for_iri, get_all_data_for_qk_iri router = APIRouter()