view service/rdf_to_mqtt/rdf_over_http.py @ 1534:df80deeef113

serve current usage as a graph Ignore-this: 76d210d576784acb639762cd6c6e6f13 darcs-hash:263305875758810b8beb38ed8b7dada825f9c4ce
author drewp <drewp@bigasterisk.com>
date Mon, 10 Feb 2020 00:01:39 -0800
parents 7cc7700302c2
children
line wrap: on
line source

from rdflib import Graph, URIRef, Literal, Namespace
from rdflib.parser import StringInputSource

ROOM = Namespace('http://projects.bigasterisk.com/room/')


def rdfGraphBody(body, headers):
    g = Graph()
    g.parse(StringInputSource(body), format='nt')
    return g


def expandQueryParamUri(txt) -> URIRef:
    if txt.startswith(':'):
        return ROOM[txt.lstrip(':')]
    # etc
    return URIRef(txt)


def rdfStatementsFromRequest(arg, body, headers):
    if arg.get('s') and arg.get('p'):
        subj = expandQueryParamUri(arg['s'][-1])
        pred = expandQueryParamUri(arg['p'][-1])
        turtleLiteral = body
        try:
            obj = Literal(float(turtleLiteral))
        except ValueError:
            obj = Literal(turtleLiteral)
        yield (subj, pred, obj)
    else:
        g = rdfGraphBody(body, headers)
        assert len(g) == 1, len(g)
        yield g.triples((None, None, None)).next()
        # could support multiple stmts