Exemple #1
0
def to_tree(graph,
            context_data=None,
            base=None,
            generate_compact=True,
            context_uri=None):
    """
    @@ TODO: add docstring describing args and returned value type
    """

    tree = {}

    # TODO: Check which prefixes are actually used when creating curies and add
    # incrementally. (Use rdflib features for this, e.g. RecursiveSerializer?)
    if not context_data:
        if generate_compact:
            context_data = dict(
                (pfx, unicode(ns)) for (pfx, ns) in graph.namespaces() if pfx
                and unicode(ns) != u"http://www.w3.org/XML/1998/namespace")

    if isinstance(context_data, Context):
        context = context_data
        context_data = context.to_dict()
    else:
        context = Context(context_data)

    if context_uri:
        tree[context.context_key] = context_uri
    elif context_data:
        tree[context.context_key] = context_data

    nodes = []

    state = (graph, context, base)

    # TODO: framing/CBD-with-startnode...
    for s in set(graph.subjects()):
        # only unreferenced.. TODO: not if more than one ref!
        if isinstance(s, URIRef) or not any(graph.subjects(None, s)):
            current = _subject_to_node(state, s)
            nodes.append(current)

    if len(nodes) == 1:
        tree.update(nodes[0])
    else:
        tree[context.graph_key] = nodes

    return tree
Exemple #2
0
def to_rdf(tree, graph, base=None, context_data=None):
    """
    @@ TODO: add docstring describing args and returned value type
    """
    context = Context()
    context.load(context_data or tree.get(CONTEXT_KEY) or {}, base)

    id_obj = tree.get(context.id_key)
    resources = id_obj
    if not isinstance(id_obj, list):
        resources = [tree]

    for term in context.terms:
        if term.iri and term.iri.endswith(('/', '#', ':')):
            graph.bind(term.key, term.iri)

    state = graph, context, base
    for node in resources:
        _add_to_graph(state, node)

    return graph