view service/mqtt_graph_bridge/rdf_over_http.py @ 1497:44de96fd0e6e

add publish to ON/OFF messages. split up the main statement handler Ignore-this: b1ec515e6873a6841b1c31c3fb7a2a36 darcs-hash:5ce3d7a66e7e45b2be2345a52e737cd0426dd985
author drewp <drewp@bigasterisk.com>
date Fri, 31 Jan 2020 23:55:27 -0800
parents 690226a7dddb
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