本文整理汇总了Python中rdflib.ConjunctiveGraph.bind方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.bind方法的具体用法?Python ConjunctiveGraph.bind怎么用?Python ConjunctiveGraph.bind使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.ConjunctiveGraph
的用法示例。
在下文中一共展示了ConjunctiveGraph.bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Config
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
class Config(object):
def __init__(self, masterGraph, hubHost):
self.etcd = etcd3.client(host=hubHost, port=9022)
self.masterGraph = masterGraph
self.hubHost = hubHost
self.configGraph = ConjunctiveGraph()
self.boards = []
self.etcPrefix = 'pi/'
self.reread()
deferToThread(self.watchEtcd)
def watchEtcd(self):
events, cancel = self.etcd.watch_prefix(self.etcPrefix)
reactor.addSystemEventTrigger('before', 'shutdown', cancel)
for ev in events:
log.info('%s changed', ev.key)
reactor.callFromThread(self.configChanged)
def configChanged(self):
self.cancelRead()
self.rereadLater = reactor.callLater(.1, self.reread)
def cancelRead(self):
if getattr(self, 'rereadLater', None):
self.rereadLater.cancel()
self.rereadLater = None
@STATS.configReread.time()
def reread(self):
self.rereadLater = None
log.info('read config')
self.configGraph = ConjunctiveGraph()
for v, md in self.etcd.get_prefix(self.etcPrefix):
log.info(' read file %r', md.key)
self.configGraph.parse(StringInputSource(v), format='n3')
self.configGraph.bind('', ROOM)
self.configGraph.bind('rdf', RDF)
# config graph is too noisy; maybe make it a separate resource
#masterGraph.patch(Patch(addGraph=self.configGraph))
self.setupBoards()
def setupBoards(self):
thisHost = Literal(hostname)
for row in self.configGraph.query(
'SELECT ?board WHERE { ?board a :PiBoard; :hostname ?h }',
initBindings=dict(h=thisHost)):
thisBoard = row.board
break
else:
log.warn("config had no board for :hostname %s. Waiting for config update." %
thisHost)
self.boards = []
return
log.info("found config for board %r" % thisBoard)
self.boards = [Board(self.configGraph, self.masterGraph, thisBoard, self.hubHost)]
self.boards[0].startPolling()
示例2: add_mediator
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def add_mediator(params):
#Write user metadata and save the rdf file
graph = Graph()
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
uri = URIRef("http://vocab.ox.ac.uk/owner/uuid:%s"%uuid.uuid4())
graph.add((uri, namespaces['foaf']['firstName'], Literal(params['firstname'])))
graph.add((uri, namespaces['foaf']['lastName'], Literal(params['lastname'])))
graph.add((uri, namespaces['foaf']['mbox'], Literal(params['email'])))
graph.add((uri, namespaces['foaf']['account'], Literal(params['username'])))
if 'title' in params and params['title']:
graph.add((uri, namespaces['foaf']['title'], Literal(params['title'])))
if 'department' in params and params['department']:
department = params['department'].split(';')
for d in department:
graph.add((uri, namespaces['dcterms']['isPartOf'], Literal(d.strip())))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']), 'w', 'utf-8')
f.write(rdf_str)
f.close()
graph2 = Graph()
graph2.parse(ag.mediatorslist)
for prefix, url in namespaces.iteritems():
graph2.bind(prefix, URIRef(url))
graph2.add((uri, namespaces['foaf']['account'], Literal(params['username'])))
rdf_str = None
rdf_str = graph2.serialize()
f = codecs.open(ag.mediatorslist, 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True
示例3: __init__
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def __init__(self, path=None):
self.__dict__ = self.__shared_state
if (self.data == None):
if (path == None):
raise ValueError("djubby's configuration MUST be initialized a first time, read http://code.google.com/p/djubby/wiki/GettingStarted")
else:
self.path = os.path.abspath(path)
logging.debug("Reading djubby's configuration from %s..." % self.path)
if (not os.path.exists(self.path)):
raise ValueError("Not found a proper file at '%s' with a configuration for djubby. Please, provide a right path" % self.path)
data = ConjunctiveGraph()
data.bind("conf", ns.config)
try:
data.load(path, format='n3')
except Exception, e:
raise ValueError("Not found a proper N3 file at '%s' with a configuration for djubby. Please, provide a valid N3 file" % self.path)
self.data = data
try:
self.graph = self.get_value("sparqlDefaultGraph")
self.endpoint = self.get_value("sparqlEndpoint")
except Exception, e:
raise ValueError("Not found the graph not the endpoint that it's supposed djubby have to query. Please, provide a right donfiguration")
logging.info("Using <%s> as default graph to query the endpoint <%s>" % (self.graph, self.endpoint))
self.__class__.__dict__['_Configuration__shared_state']["data"] = data #FIXME
示例4: parse
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def parse(self, source, graph, encoding="utf-8"):
if encoding not in [None, "utf-8"]:
raise Exception(
("TriG files are always utf-8 encoded, ",
"I was passed: %s") % encoding)
# we're currently being handed a Graph, not a ConjunctiveGraph
assert graph.store.context_aware, "TriG Parser needs a context-aware store!"
conj_graph = ConjunctiveGraph(store=graph.store, identifier=graph.identifier)
conj_graph.default_context = graph # TODO: CG __init__ should have a
# default_context arg
# TODO: update N3Processor so that it can use conj_graph as the sink
conj_graph.namespace_manager = graph.namespace_manager
sink = RDFSink(conj_graph)
baseURI = conj_graph.absolutize(
source.getPublicId() or source.getSystemId() or "")
p = TrigSinkParser(sink, baseURI=baseURI, turtle=True)
p.loadStream(source.getByteStream())
for prefix, namespace in p._bindings.items():
conj_graph.bind(prefix, namespace)
示例5: change_status
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def change_status(vocabprefix, uri, predicate, message, action):
if not action in ['add', 'remove']:
return False
vocab_uri = URIRef(uri)
vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
vocabstatusfile = os.path.join(vocabdir, "status.rdf")
if not os.path.isfile(vocabstatusfile):
return False
graph = Graph()
graph.parse(vocabstatusfile)
predicate = predicate.split(':')
ns = predicate[0]
term = predicate[1]
if message and (message.startswith('http://') or message.startswith('file://')):
message = URIRef(message)
elif message:
message = Literal(message)
if action == 'add':
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
graph.add((vocab_uri, namespaces[ns][term], message))
elif action == 'remove':
graph.remove((vocab_uri, namespaces[ns][term], message))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(vocabstatusfile, 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True
示例6: update_mediator
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def update_mediator(params):
#Write user metadata and save the rdf file
if not ('username' in params and params['username']):
return False
det = get_mediator_details(params['username'])
graph = Graph()
graph.parse(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']))
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
uri = URIRef(det['uri'])
if 'firstname' in params and params['firstname']:
graph.remove((uri, namespaces['foaf']['firstName'], None))
graph.add((uri, namespaces['foaf']['firstName'], Literal(params['firstname'])))
if 'lastname' in params and params['lastname']:
graph.remove((uri, namespaces['foaf']['lastName'], None))
graph.add((uri, namespaces['foaf']['lastName'], Literal(params['lastname'])))
if 'email' in params and params['email']:
graph.remove((uri, namespaces['foaf']['mbox'], None))
graph.add((uri, namespaces['foaf']['mbox'], Literal(params['email'])))
if 'title' in params and params['title']:
graph.remove((uri, namespaces['foaf']['title'], None))
graph.add((uri, namespaces['foaf']['title'], Literal(params['title'])))
if 'department' in params and params['department']:
graph.remove((uri, namespaces['dcterms']['isPartOf'], None))
department = params['department'].split(';')
for d in department:
graph.add((uri, namespaces['dcterms']['isPartOf'], Literal(d.strip())))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']), 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True
示例7: get_rdf_template
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def get_rdf_template(item_uri, item_id):
g = ConjunctiveGraph(identifier=item_uri)
g.bind('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
g.bind('dcterms', 'http://purl.org/dc/terms/')
g.add((URIRef(item_uri), URIRef('http://purl.org/dc/terms/identifier'), Literal(item_id)))
data2 = g.serialize(format='xml', encoding="utf-8") + '\n'
return data2
示例8: __init__
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def __init__(self, additional_bindings=list()):
store = ConjunctiveGraph(identifier='default')
nsBindings = [('quit', QUIT), ('foaf', FOAF), ('prov', PROV)]
for prefix, namespace in nsBindings + additional_bindings:
store.bind(prefix, namespace)
super().__init__(store=store)
示例9: load_sentence
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def load_sentence(self, rdf_triples):
"""
Load the given triples into the triple store
"""
g = ConjunctiveGraph()
g.bind("base", BASE)
for triple in rdf_triples:
g.add(triple)
self.soh.add_triples(g, clear=True)
示例10: Config
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
class Config(object):
def __init__(self, masterGraph):
self.graph = ConjunctiveGraph()
log.info('read config')
for f in os.listdir('config'):
if f.startswith('.'): continue
self.graph.parse('config/%s' % f, format='n3')
log.info(' parsed %s', f)
self.graph.bind('', ROOM)
self.graph.bind('rdf', RDF)
示例11: createGlobalGraph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def createGlobalGraph(cls, gns):
"""
Creates a global graph representing a global context.
@type gns: str
@param gns: the global namespace
"""
globalGraph = ConjunctiveGraph()
globalGraph.bind("owl", OWL)
globalGraph.bind(gns[gns.rfind("/")+1:len(gns)-1], gns)
return globalGraph
示例12: __init__
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def __init__(self, base_uri):
graph = ConjunctiveGraph()
self._graph = graph
self._base_uri = self._validateURI(base_uri)
self._uniq_ids = dict()
# bind prefixes to namespaces
graph.bind('dbp', DBPEDIA)
graph.bind('dct', DCTERMS)
graph.bind('dcat', DCAT)
graph.bind('lang', LANG)
示例13: render
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def render(self, data, accepted_media_type=None, renderer_context=None):
jsonld = super(TurtleRenderer, self)\
.render(data, accepted_media_type, renderer_context)
g = ConjunctiveGraph()
for ns, uri in list(NAMESPACES.items()):
g.bind(ns, Namespace(uri))
g.parse(data=jsonld, format='json-ld')
return g.serialize(format='turtle')
示例14: create_temporal_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def create_temporal_graph(self, resources):
graph = ConjunctiveGraph()
if resources:
for resource in resources:
triples = self.graph.triples((URIRef(resource), None, None))
for triple in triples:
graph.add(triple)
#Bind namespaces to graph
for ns in NSBINDINGS:
graph.bind(ns, NSBINDINGS[ns])
return graph
示例15: add_ref_vocab
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import bind [as 别名]
def add_ref_vocab(vocabprefix, source_uri):
vocab_uri = URIRef("http://vocab.ox.ac.uk/%s"%vocabprefix)
graph = Graph()
if os.path.isfile(ag.vocabulariesref):
graph.parse(ag.vocabulariesref)
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
graph.add((URIRef(vocab_uri), namespaces['dcterms']['isVersionOf'], URIRef(source_uri)))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(ag.vocabulariesref, 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True