Coverage for apis_core/generic/renderers.py: 0%
48 statements
« prev ^ index » next coverage.py v7.5.3, created at 2025-06-25 10:00 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2025-06-25 10:00 +0000
1import logging
3from rdflib import Graph
4from rest_framework import renderers
5from rest_framework.exceptions import APIException
7logger = logging.getLogger(__name__)
10class GenericRDFBaseRenderer(renderers.BaseRenderer):
11 """
12 Base class to render RDF graphs to various formats.
13 This renderer expects the serialized data to either be a rdflib grap **or**
14 to contain a list of rdflib graphs. If it works with a list of graphs, those
15 are combined to one graph.
16 This graph is then serialized and the result is returned. The serialization
17 format can be set using the `rdflib_format` attribute. If this is not set, the
18 `format` attribute of the renderer is used as serialization format (this is the
19 format as it is used by the Django Rest Framework for content negotiation.
20 """
22 format = "ttl"
23 rdflib_format = None
25 def render(self, data, accepted_media_type=None, renderer_context=None):
26 result = Graph()
28 match data:
29 case {"results": results, **rest}: # noqa: F841
30 # Handle case where data is a dict with multiple graphs
31 for graph in results:
32 if isinstance(graph, Graph):
33 # Merge triples
34 for triple in graph:
35 result.add(triple)
36 # Merge namespace bindings
37 for prefix, namespace in graph.namespaces():
38 result.bind(prefix, namespace, override=False)
39 case {"detail": detail}:
40 raise APIException(detail)
41 case Graph():
42 # Handle case where data is a single graph
43 result = data
44 # Ensure namespaces are properly bound in the single graph case
45 for prefix, namespace in data.namespaces():
46 result.bind(prefix, namespace, override=False)
47 case _:
48 raise ValueError(
49 "Invalid data format. Expected rdflib Graph or dict with 'results' key containing graphs"
50 )
51 serialization_format = self.rdflib_format or self.format
52 return result.serialize(format=serialization_format)
55class GenericRDFTurtleRenderer(GenericRDFBaseRenderer):
56 format = "ttl"
57 media_type = "text/turtle"
58 rdflib_format = "turtle"
61class GenericRDFXMLRenderer(GenericRDFBaseRenderer):
62 format = "rdf"
63 media_type = "application/rdf+xml"
64 rdflib_format = "xml"
67class GenericRDFN3Renderer(GenericRDFBaseRenderer):
68 format = "rdf"
69 media_type = "text/n3"
70 rdflib_format = "n3"
73class CidocTTLRenderer(GenericRDFBaseRenderer):
74 format = "cidoc"
75 media_type = "text/ttl"
76 rdflib_format = "ttl"
79class CidocXMLRenderer(GenericRDFBaseRenderer):
80 format = "cidoc"
81 media_type = "application/rdf+xml"
82 rdflib_format = "xml"