本文整理汇总了Python中rdflib.URIRef.n3方法的典型用法代码示例。如果您正苦于以下问题:Python URIRef.n3方法的具体用法?Python URIRef.n3怎么用?Python URIRef.n3使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.URIRef
的用法示例。
在下文中一共展示了URIRef.n3方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: discussion_as_graph
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def discussion_as_graph(self, discussion_id):
from assembl.models import Discussion, AgentProfile
local_uri = self.local_uri()
discussion = Discussion.get(discussion_id)
d_storage_name = self.discussion_storage_name()
d_graph_iri = URIRef(self.discussion_graph_iri())
v = get_virtuoso(self.session, d_storage_name)
discussion_uri = URIRef(
Discussion.uri_generic(discussion_id, local_uri))
subjects = [s for (s,) in v.query(
"""SELECT DISTINCT ?s WHERE {
?s assembl:in_conversation %s }""" % (discussion_uri.n3()))]
subjects.append(discussion_uri)
participant_ids = list(discussion.get_participants(True))
profiles = {URIRef(AgentProfile.uri_generic(id, local_uri))
for id in participant_ids}
subjects.extend(profiles)
# add pseudo-accounts
subjects.extend((URIRef("%sAgentAccount/%d" % (local_uri, id))
for id in participant_ids))
# print len(subjects)
cg = ConjunctiveGraph(identifier=d_graph_iri)
self.add_subject_data(v, cg, subjects)
# add relationships of non-pseudo accounts
for ((account, p, profile), g) in v.triples((None, SIOC.account_of, None)):
if profile in profiles:
cg.add((account, SIOC.account_of, profile, g))
# Tempting: simplify with this.
# cg.add((profile, FOAF.account, account, g))
for (s, o, g) in v.query(
'''SELECT ?s ?o ?g WHERE {
GRAPH ?g {?s catalyst:expressesIdea ?o } .
?o assembl:in_conversation %s }''' % (discussion_uri.n3())):
cg.add((s, CATALYST.expressesIdea, o, g))
return cg
示例2: discussion_as_graph
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def discussion_as_graph(self, discussion_id):
self.ensure_discussion_storage(None)
from assembl.models import Discussion
d_storage_name = self.discussion_storage_name()
d_graph_iri = URIRef(self.discussion_graph_iri())
v = get_virtuoso(self.session, d_storage_name)
discussion_uri = URIRef(
Discussion.uri_generic(discussion_id, self.local_uri()))
subjects = list(v.query(
"""SELECT DISTINCT ?s WHERE {
?s assembl:in_conversation %s }""" % (discussion_uri.n3())))
subjects.append([discussion_uri])
# print len(subjects)
cg = ConjunctiveGraph(identifier=d_graph_iri)
for (s,) in subjects:
# Absurdly slow. DISTINCT speeds up a lot, but I get numbers.
for p, o in v.query(
'SELECT ?p ?o WHERE { graph %s { %s ?p ?o }}' % (
d_graph_iri.n3(), s.n3())):
cg.add((s, p, o))
for (s, o, g) in v.query(
'''SELECT ?s ?o ?g WHERE {
GRAPH ?g {?s catalyst:expressesIdea ?o } .
?o assembl:in_conversation %s }''' % (discussion_uri.n3())):
cg.add((s, CATALYST.expressesIdea, o, g))
# TODO: Add roles
return cg
示例3: view
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def view(rtype, rid):
if '.' in rid:
rid, suffix = rid.rsplit('.', 1)
else:
suffix = None
path = rtype + '/' + rid
uri = URIRef(app.config['RESOURCE_BASE'] + path)
#if template:
services = app.config['SERVICES']
rq = render_template("queries/%s.rq" % rtype,
prefixes=RQ_PREFIXES, this=uri.n3(), services=services)
fmt = _conneg_format(suffix)
if fmt == 'rq':
return rq, 200, {'Content-Type': 'text/plain'}
res = run_query(app.config['ENDPOINT'], rq)
#else:
# url = data_base + path + '.n3'
# res = requests.get(url)
graph = to_graph(res.content)
this = graph.resource(uri)
if fmt in ('html', 'xhtml'):
return render_template(rtype + '.html',
path=path, this=this, curies=graph.qname)
else:
headers = {'Content-Type': MIMETYPES.get(fmt) or 'text/plain'}
fmt = {'rdf': 'xml', 'ttl': 'turtle'}.get(fmt) or fmt
return graph.serialize(format=fmt), 200, headers
示例4: instance_view_jsonld
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def instance_view_jsonld(request):
from assembl.semantic.virtuoso_mapping import AssemblQuadStorageManager
from rdflib import URIRef, ConjunctiveGraph
ctx = request.context
user_id = authenticated_userid(request) or Everyone
permissions = get_permissions(
user_id, ctx.get_discussion_id())
instance = ctx._instance
if not instance.user_can(user_id, CrudPermissions.READ, permissions):
return HTTPUnauthorized()
discussion = ctx.get_instance_of_class(Discussion)
if not discussion:
raise HTTPNotFound()
aqsm = AssemblQuadStorageManager()
uri = URIRef(aqsm.local_uri() + instance.uri()[6:])
d_storage_name = aqsm.discussion_storage_name(discussion.id)
v = get_virtuoso(instance.db, d_storage_name)
cg = ConjunctiveGraph(v, d_storage_name)
result = cg.triples((uri, None, None))
#result = v.query('select ?p ?o ?g where {graph ?g {<%s> ?p ?o}}' % uri)
# Something is wrong here.
triples = '\n'.join([
'%s %s %s.' % (uri.n3(), p.n3(), o.n3())
for (s, p, o) in result
if '_with_no_name_entry' not in o])
return aqsm.quads_to_jsonld(triples)
示例5: bulk_update
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def bulk_update(self, named_graph, graph, size, is_add=True):
"""
Bulk adds or deletes. Triples are chunked into n size groups before
sending to API. This prevents the API endpoint from timing out.
"""
context = URIRef(named_graph)
total = len(graph)
if total > 0:
for set_size, nt in self.nt_yielder(graph, size):
if is_add is True:
logger.debug("Adding {} statements to <{}>.".format(set_size, named_graph))
self.update(u'INSERT DATA { GRAPH %s { %s } }' % (context.n3(), nt))
else:
logger.debug("Removing {} statements from <{}>.".format(set_size, named_graph))
self.update(u'DELETE DATA { GRAPH %s { %s } }' % (context.n3(), nt))
return total
示例6: get_synthesis_contributors
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def get_synthesis_contributors(self, id_only=True):
# author of important extracts
from .idea_content_link import Extract
from .auth import AgentProfile
from .post import Post
from sqlalchemy.sql.functions import count
local_uri = AssemblQuadStorageManager.local_uri()
discussion_storage = \
AssemblQuadStorageManager.discussion_storage_name()
idea_uri = URIRef(self.uri(local_uri))
clause = '''select distinct ?annotation where {
%s idea:includes* ?ideaP .
?annotation assembl:resourceExpressesIdea ?ideaP }'''
extract_ids = [x for (x,) in self.db.execute(
SparqlClause(clause % (
idea_uri.n3(),),
quad_storage=discussion_storage.n3()))]
r = list(self.db.query(AgentProfile.id, count(Extract.id)).join(
Post, Post.creator_id==AgentProfile.id).join(Extract).filter(
Extract.important == True, Extract.id.in_(extract_ids)))
r.sort(key=lambda x: x[1], reverse=True)
if id_only:
return [AgentProfile.uri_generic(a) for (a, ce) in r]
else:
ids = [a for (a, ce) in r]
order = {id: order for (order, id) in enumerate(ids)}
agents = self.db.query(AgentProfile).filter(AgentProfile.id.in_(ids)).all()
agents.sort(key=lambda a: order[a.id])
return agents
示例7: ContentProvider
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
class ContentProvider(object):
#implements(IContentProvider)
def __init__(self, config):
self.config = config
self.jena = JenaHelper(config)
self.harvester = URIRef(config['harvesteruri'])
data = self.jena.graphquery("DESCRIBE %s" % self.harvester.n3())
#import pdb; pdb.set_trace()
self.originatingSource = data.value(self.harvester, ANDS.originatingSource) or Literal(config['originatingsource'])
self.groupDescription = data.value(self.harvester, ANDS.groupDescription) or Literal(config['groupdescription'])
self.item_sparql_query = resource_string(__name__, "item_sparql.sparql")
def set_logger(self, log):
"""Set the logger instance for this class
"""
self.log = log
def update(self, from_date=None):
"""Harvests new content added since from_date
returns a list of content_ids that were changed/added,
this should be called before get_contents is called
"""
query = resource_string(__name__, "items_to_harvest.sparql")
self._content = self.jena.selectquery(query % {'harvester': self.harvester})
return self._content
def count(self):
"""Returns number of content objects in the repository
returns None if number is unknown, this should not be
called before update is called
"""
return len(self._content)
def get_content_ids(self):
"""returns a list/generator of content_ids
"""
return self._content
def get_content_by_id(self, id):
"""Return content of a specific id
"""
# assume id is URIRef instance
g = Graph(identifier=URIRef(id))
#print self.item_sparql_query %{"subject":id, 'harvester': self.harvester}
data = self.jena.graphquery(self.item_sparql_query %{"subject": id,
'harvester': self.harvester}, g)
#print data
# FIXME: make tese conditional
data.add((URIRef(id), ANDS.originatingSource, self.originatingSource))
data.add((URIRef(id), ANDS.groupDescription, self.groupDescription))
return data
示例8: test_creation_with_unknown_ns
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def test_creation_with_unknown_ns(self):
uri = 'http://localhost:8000/resource/aggregation/ton-smits-huis/454'
predicate = RDFPredicate(uri)
graph = Graph()
graph.add((URIRef(uri), FOAF.name, Literal("sjoerd")))
subject = list(graph.subjects())[0]
uri_ref = URIRef(uri)
assert uri_ref.n3() == "ns1:454"
assert predicate is not None
assert predicate.label is not None
示例9: match_sparql_ask
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def match_sparql_ask(transition, event, token, fsa):
"""
The 'sparql-ask' matcher.
With this matcher,
transition conditions are interpreted as the WHERE clause of a SPARQL Ask query,
where variable ?obs is bound to the considered obsel,
and prefix m: is bound to the source trace URI.
"""
m_ns = fsa.source.model_uri
if m_ns[-1] != '/' and m_ns[-1] != '#':
m_ns += '#'
history = token and token.get('history_events')
if history:
pred = URIRef(history[-1])
first = URIRef(history[0])
else:
pred = None
first = None
condition = transition['condition']
## this would be the correct way to do it
# initBindings = { "obs": URIRef(event), "pred": pred, "first": first }
## unfortunately, Virtuoso does not support VALUES clauses after the ASK clause,
## which is how SPARQLUpdateStore handles initBindings
## so we generate that clause in the condition instead
condition = """
BIND (%s as ?obs)
BIND (%s as ?pred)
BIND (%s as ?first)
""" % (
URIRef(event).n3(),
pred.n3() if pred else '""', # simulating NULL
first.n3() if first else '""', # simulating NULL
) + condition
## thank you for nothing Virtuoso :-(
return fsa.source_obsels_graph.query(
"ASK { %s }" % condition,
initNs={"": KTBS, "m": m_ns},
# initBindings=initBindings, # not supported by Virtuoso :-(
).askAnswer
示例10: check_valid_uri
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def check_valid_uri(self, uri):
""" checks to see if a uri is valid """
valid = False
if isinstance(uri, str):
uri_out = False
try:
uri_test = URIRef(uri)
uri_out = uri_test.n3()
except:
# some sort of error thrown, so not valid
valid = False
if isinstance(uri_out, str):
valid = True
return valid
示例11: term
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def term(self, term, use_prefix=True):
if isinstance(term, Namespace):
term = URIRef(term)
if term is None:
return RDF.nil
elif not hasattr(term, 'n3'):
return self.term(Literal(term))
elif use_prefix and isinstance(term, URIRef):
return self.uri(term)
elif isinstance(term, Literal):
if term.datatype in (XSD.double, XSD.integer, XSD.float, XSD.boolean):
return unicode(term).lower()
elif isinstance(term, Namespace):
return unicode(term)
return term.n3()
示例12: get_idea_ids_showing_post
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def get_idea_ids_showing_post(cls, post_id):
"Given a post, give the ID of the ideas that show this message"
# This works because of a virtuoso bug...
# where DISTINCT gives IDs instead of URIs.
from .generic import Content
discussion_storage = \
AssemblQuadStorageManager.discussion_storage_name()
post_uri = URIRef(Content.uri_generic(
post_id, AssemblQuadStorageManager.local_uri()))
return [int(id) for (id,) in cls.default_db.execute(SparqlClause(
'''select distinct ?idea where {
%s sioc:reply_of* ?post .
?post assembl:postLinkedToIdea ?ideaP .
?idea idea:includes* ?ideaP }''' % (post_uri.n3(),),
quad_storage=discussion_storage.n3()))]
示例13: canvas_and_images_graph
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def canvas_and_images_graph(graph, canvas_uri):
canvas_uri = URIRef(canvas_uri)
canvas_graph = Graph()
canvas_graph += graph.triples((canvas_uri, None, None))
qres = graph.query("""SELECT ?image_anno ?image WHERE {
?image_anno a oa:Annotation .
?image_anno oa:hasTarget %s .
?image_anno oa:hasBody ?image .
?image a ?type .
FILTER(?type = dcmitype:Image || ?type = dms:Image || ?type = dms:ImageChoice) .
}""" % (canvas_uri.n3()), initNs=ns)
for image_anno, image in qres:
canvas_graph += graph.triples_choices(([image_anno, image], None, None))
return canvas_graph
示例14: term
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def term(self, term, use_prefix=True):
if isinstance(term, (Namespace, ClosedNamespace)):
term = URIRef(namespace_to_uri(term))
if term is None:
return RDF.nil
elif not hasattr(term, 'n3'):
return self.term(Literal(term))
elif use_prefix and isinstance(term, URIRef):
return self.uri(term)
elif isinstance(term, Literal):
if term.datatype in (XSD.double, XSD.integer, XSD.float, XSD.boolean):
return unicode(term).lower()
elif use_prefix and term.datatype: # Abbreviate datatype if possible
datatype_term = self.uri(term.datatype)
return '"%s"^^%s' % (term, datatype_term)
elif isinstance(term, Namespace):
return unicode(term)
return term.n3()
示例15: get_contributors
# 需要导入模块: from rdflib import URIRef [as 别名]
# 或者: from rdflib.URIRef import n3 [as 别名]
def get_contributors(self):
# anyone who contributed to any of the idea's posts
local_uri = AssemblQuadStorageManager.local_uri()
discussion_storage = \
AssemblQuadStorageManager.discussion_storage_name()
idea_uri = URIRef(self.uri(local_uri))
clause = '''select count(distinct ?postP), count(distinct ?post), ?author where {
%s idea:includes* ?ideaP .
?postP assembl:postLinkedToIdea ?ideaP .
?post sioc:reply_of* ?postP .
?post sioc:has_creator ?author }'''
r = self.db.execute(
SparqlClause(clause % (
idea_uri.n3(),),
quad_storage=discussion_storage.n3()))
r = [(int(cpp), int(cp), 'local:AgentProfile/' + a.rsplit('/',1)[1]
) for (cpp, cp, a) in r]
r.sort(reverse=True)
return [a for (cpp, cp, a) in r]