cubicweb/rdf.py
changeset 12891 eb0cd6060062
child 12892 0df0db725f07
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cubicweb/rdf.py	Fri Feb 14 18:15:55 2020 +0100
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+# copyright 2019 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# contact http://www.logilab.fr -- mailto:contact@logilab.fr
+#
+# This program is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+from rdflib import Namespace, ConjunctiveGraph, plugin
+import rdflib_jsonld  # noqa
+
+plugin.register("jsonld", plugin.Serializer, "rdflib_jsonld.serializer", "JsonLDSerializer")
+
+RDF_MIMETYPE_TO_FORMAT = {
+    'application/rdf+xml': 'xml',
+    'text/turtle': 'turtle',
+    'text/n3': 'n3',
+    'application/n-quads': 'nquads',
+    'application/n-triples': 'nt',
+    'application/trig': 'trig',
+    'application/ld+json': 'json-ld',
+}
+
+namespaces = {
+    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+    "schema": "http://schema.org/",
+}
+
+NS_VARS = {ns: Namespace(uri) for ns, uri in namespaces.items()}
+
+
+# dict: name of CWEType -> list of regid of adapters derived from EntityRDFAdapter
+ETYPES_ADAPTERS = {
+}
+
+
+def conjunctive_graph():
+    """factory to build a ``ConjunctiveGraph`` and bind all namespaces
+    """
+    graph = ConjunctiveGraph()
+    for vocab, rdfns in NS_VARS.items():
+        graph.bind(vocab, rdfns)
+    return graph
+
+
+def iter_rdf_adapters(entity):
+    for adapter_id in ETYPES_ADAPTERS.get(entity.__regid__, ()):
+        adapter = entity.cw_adapt_to(adapter_id)
+        if adapter:
+            yield adapter
+
+
+def add_entity_to_graph(graph, entity):
+    for adapter in iter_rdf_adapters(entity):
+        for triple in adapter.triples():
+            graph.add(triple)