From b24f7c6143dd1182819aa74d87d728c6df6df9cd Mon Sep 17 00:00:00 2001 From: Munyoki Kilyungi Date: Fri, 27 Oct 2023 16:21:28 +0300 Subject: Add functions that wrap around the common jsonld patterns. * gn3/db/rdf.py: Import jsonld. (query_frame_and_compact, query_and_compact, query_and_frame): New functions. Signed-off-by: Munyoki Kilyungi --- gn3/db/rdf.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'gn3/db/rdf.py') diff --git a/gn3/db/rdf.py b/gn3/db/rdf.py index 2140694..ae6b0f2 100644 --- a/gn3/db/rdf.py +++ b/gn3/db/rdf.py @@ -6,6 +6,7 @@ This module is a collection of functions that handle SPARQL queries. import json from SPARQLWrapper import SPARQLWrapper +from pyld import jsonld # type: ignore PREFIXES = { @@ -44,3 +45,27 @@ def sparql_construct_query(query: str, endpoint: str) -> dict: sparql.setQuery(query) results = sparql.queryAndConvert() return json.loads(results.serialize(format="json-ld")) # type: ignore + + +def query_frame_and_compact(query: str, context: dict, endpoint: str) -> dict: + """Frame and then compact the results given a context""" + results = sparql_construct_query(query, endpoint) + if not results: + return {} + return jsonld.compact(jsonld.frame(results, context), context) + + +def query_and_compact(query: str, context: dict, endpoint: str) -> dict: + """Compact the results given a context""" + results = sparql_construct_query(query, endpoint) + if not results: + return {} + return jsonld.compact(results, context) + + +def query_and_frame(query: str, context: dict, endpoint: str) -> dict: + """Frame the results given a context""" + results = sparql_construct_query(query, endpoint) + if not results: + return {} + return jsonld.frame(results, context) -- cgit v1.2.3