当前位置: 首页>>代码示例>>Python>>正文


Python ConjunctiveGraph.close方法代码示例

本文整理汇总了Python中rdflib.graph.ConjunctiveGraph.close方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.close方法的具体用法?Python ConjunctiveGraph.close怎么用?Python ConjunctiveGraph.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rdflib.graph.ConjunctiveGraph的用法示例。


在下文中一共展示了ConjunctiveGraph.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update_list

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
def update_list():
    """
    Reads the triple store looking for twitter usernames and adds 
    them to the dev8d list.
    """
    g = ConjunctiveGraph("Sleepycat")
    g.open("store")

    # get oauth client in order
    credentials = get_credentials()
    consumer = oauth.Consumer(credentials['key'], credentials['secret'])
    client = oauth.Client(consumer, credentials['access_token'])
    list_update_url = 'http://api.twitter.com/1/%s/%s/members.json' % \
        (credentials['list_owner'], credentials['list_name'])

    # create the list if necessary
    create_list(credentials['list_owner'], credentials['list_name'], client)

    # look at all the twitter usernames and add them to the list
    for twitter_username in g.objects(predicate=w['Twitter']):
        id = twitter_user_id(twitter_username, client)
        if id:
            logging.info("adding %s (%s) to list" % (twitter_username, id))
            body = "id=%s" % id
            resp, content = client.request(list_update_url, 'POST', body=body)
        else:
            logging.error("unable to get twitter id for %s" % twitter_username)
    g.close()
开发者ID:edsu,项目名称:dev8d-linked-data,代码行数:30,代码来源:twitter_list.py

示例2: TestBDBTransactions

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
class TestBDBTransactions(unittest.TestCase):
    non_core = True

    def setUp(self):
        self.graph = ConjunctiveGraph(store="BerkeleyDB")
        self.path = mkdtemp()
        self.graph.open(self.path, create=True)
                    
    def tearDown(self):
        self.graph.close()

    def get_context(self, identifier):
        assert isinstance(identifier, URIRef) or \
               isinstance(identifier, BNode), type(identifier)
        return Graph(store=self.graph.store, identifier=identifier,
                         namespace_manager=self)

    def __manyOpsManyThreads(self, worker, workers=10, triples=1000, input=[]):
        all_ops = []
        
        pool = []
        for i in range(0, workers):
            t = Thread(target=worker, args=(all_ops, self.graph, triples), kwargs={'input':input})
            pool.append(t)
            t.start()

        for t in pool:
            t.join()

        return all_ops
    
    def testAddManyManyThreads(self):
        # TODO: sometimes this test leads to TypeError exceptions?
        w = 4
        t = 1000
        self.__manyOpsManyThreads(worker_add, workers=w, triples=t)
        #print "graph size after finish: ", len(self.graph)
        self.failUnless(len(self.graph) == w*t)
    
    def testRemove(self):
        ops = self.__manyOpsManyThreads(worker_add, workers=1, triples=10)
        self.__manyOpsManyThreads(worker_remove, workers=1, triples=7, input=ops)
        #print "graph size after finish: ", len(self.graph)
        self.failUnless(len(self.graph) == 3)

    def testRemoveAll(self):
        ops = self.__manyOpsManyThreads(worker_add, workers=1, triples=10)
        
        try:
            self.graph.remove((None, None, None))
        except Exception, e:
            #print "Could not remove all: ", e
            raise e
            
        #print "graph size after finish: ", len(self.graph)
        self.failUnless(len(self.graph) == 0)
开发者ID:alcides,项目名称:rdflib,代码行数:58,代码来源:test_bdb_transaction.py

示例3: testModel

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
    def testModel(self):
        g = ConjunctiveGraph()
        g.parse(data=test_data, format="n3")
        i = 0
        for s, p, o in g:
            if isinstance(s, Graph):
                i += 1
        self.assertEquals(i, 3)
        self.assertEquals(len(list(g.contexts())), 13)

        g.close()
开发者ID:suzuken,项目名称:xbrlparser,代码行数:13,代码来源:test_n3.py

示例4: setUp

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
class TestBDBOptimized:
    non_core = True
    bsddb = True

    def setUp(self):
        self.graph = ConjunctiveGraph(store="BDBOptimized")
        self.path = mkdtemp()
        self.graph.open(self.path, create=True)

    def tearDown(self):
        self.graph.close()
开发者ID:alcides,项目名称:rdflib,代码行数:13,代码来源:test_bdb_optimized.py

示例5: rdf_description

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
def rdf_description(name, notation='xml' ):
    """
    Funtion takes  title of node, and rdf notation.
    """
    valid_formats = ["xml", "n3", "ntriples", "trix"]
    default_graph_uri = "http://gstudio.gnowledge.org/rdfstore"
    configString = "/var/tmp/rdfstore"

    # Get the Sleepycat plugin.
    store = plugin.get('Sleepycat', Store)('rdfstore')

    # Open previously created store, or create it if it doesn't exist yet
    graph = Graph(store="Sleepycat",
               identifier = URIRef(default_graph_uri))
    path = mkdtemp()
    rt = graph.open(path, create=False)
    if rt == NO_STORE:
    #There is no underlying Sleepycat infrastructure, create it
        graph.open(path, create=True)
    else:
        assert rt == VALID_STORE, "The underlying store is corrupt"


    # Now we'll add some triples to the graph & commit the changes
    rdflib = Namespace('http://sbox.gnowledge.org/gstudio/')
    graph.bind("gstudio", "http://gnowledge.org/")
    exclusion_fields = ["id", "rght", "node_ptr_id", "image", "lft", "_state", "_altnames_cache", "_tags_cache", "nid_ptr_id", "_mptt_cached_fields"]
    node=Objecttype.objects.get(title=name)
    node_dict=node.__dict__

    subject=str(node_dict['id'])
    for key in node_dict:
        if key not in exclusion_fields:
            predicate=str(key)
            pobject=str(node_dict[predicate])
            graph.add((rdflib[subject], rdflib[predicate], Literal(pobject)))
     
     
    graph.commit()

    print graph.serialize(format=notation)

    graph.close()
开发者ID:Big-Data,项目名称:gnowsys-studio,代码行数:45,代码来源:rdf.py

示例6: testFormulaStore

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
def testFormulaStore(store="default", configString=None):
    try:
        g = ConjunctiveGraph(store=store)
    except ImportError:
        raise SkipTest("Dependencies for store '%s' not available!" % store)

    if configString:
        g.destroy(configString)
        g.open(configString)
    else:
        if store == 'SQLite':
            _, path = mkstemp(prefix='test', dir='/tmp', suffix='.sqlite')
            g.open(path, create=True)
        else:
            g.open(mkdtemp(), create=True)

    g.parse(data=testN3, format="n3")
    try:
        for s, p, o in g.triples((None, implies, None)):
            formulaA = s
            formulaB = o

        assert type(formulaA) == QuotedGraph and type(formulaB) == QuotedGraph
        # a = URIRef('http://test/a')
        b = URIRef('http://test/b')
        c = URIRef('http://test/c')
        d = URIRef('http://test/d')
        v = Variable('y')

        universe = ConjunctiveGraph(g.store)

        #test formula as terms
        assert len(list(universe.triples((formulaA, implies, formulaB)))) == 1

        #test variable as term and variable roundtrip
        assert len(list(formulaB.triples((None, None, v)))) == 1
        for s, p, o in formulaB.triples((None, d, None)):
            if o != c:
                assert isinstance(o, Variable)
                assert o == v
        s = list(universe.subjects(RDF.type, RDFS.Class))[0]
        assert isinstance(s, BNode)
        assert len(list(universe.triples((None, implies, None)))) == 1
        assert len(list(universe.triples((None, RDF.type, None)))) == 1
        assert len(list(formulaA.triples((None, RDF.type, None)))) == 1
        assert len(list(formulaA.triples((None, None, None)))) == 2
        assert len(list(formulaB.triples((None, None, None)))) == 2
        assert len(list(universe.triples((None, None, None)))) == 3
        assert len(list(formulaB.triples(
            (None, URIRef('http://test/d'), None)))) == 2
        assert len(list(universe.triples(
            (None, URIRef('http://test/d'), None)))) == 1

        # #context tests
        # #test contexts with triple argument
        # assert len(list(universe.contexts((a, d, c)))) == 1, \
        #                     [ct for ct in universe.contexts((a, d, c))]

        # FAIL: test.test_graph_formula.testFormulaStores('SQLite',)
        # --------------------------------------------------------------------
        # Traceback (most recent call last):
        #   File ".../site-packages/nose/case.py", line 197, in runTest
        #     self.test(*self.arg)
        #   File ".../test_graph_formula.py", line 80, in testFormulaStore
        #     [ct for ct in universe.contexts((a, d, c))]
        # AssertionError: [
        #     <Graph identifier=N52fd4417ef7641089b2e4045ef19ad87
        #        (<class 'rdflib.graph.Graph'>)>,
        #     <Graph identifier=_:Formula16 (<class 'rdflib.graph.Graph'>)>
        #     ]

        #Remove test cases
        universe.remove((None, implies, None))
        assert len(list(universe.triples((None, implies, None)))) == 0
        assert len(list(formulaA.triples((None, None, None)))) == 2
        assert len(list(formulaB.triples((None, None, None)))) == 2

        formulaA.remove((None, b, None))
        assert len(list(formulaA.triples((None, None, None)))) == 1
        formulaA.remove((None, RDF.type, None))
        assert len(list(formulaA.triples((None, None, None)))) == 0

        universe.remove((None, RDF.type, RDFS.Class))

        #remove_context tests
        universe.remove_context(formulaB)
        assert len(list(universe.triples((None, RDF.type, None)))) == 0
        assert len(universe) == 1
        assert len(formulaB) == 0

        universe.remove((None, None, None))
        assert len(universe) == 0

        g.close()
        if store == 'SQLite':
            os.unlink(path)
        else:
            g.store.destroy(configString)
    except:
        g.close()
#.........这里部分代码省略.........
开发者ID:Dataliberate,项目名称:rdflib,代码行数:103,代码来源:test_graph_formula.py

示例7: ContextTest

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
class ContextTest(test.TestCase):
    """
    Testing different contexts.

    Heavily based on https://github.com/RDFLib/rdflib-postgresql/blob/master/test/context_case.py
    """
    store_name = "Django"
    storetest = True
    path = ""
    create = True

    michel = URIRef(u'michel')
    tarek = URIRef(u'tarek')
    bob = URIRef(u'bob')
    likes = URIRef(u'likes')
    hates = URIRef(u'hates')
    pizza = URIRef(u'pizza')
    cheese = URIRef(u'cheese')
    c1 = URIRef(u'context-1')
    c2 = URIRef(u'context-2')

    def setUp(self):
        self.graph = ConjunctiveGraph(store=self.store_name)
        self.graph.destroy(self.path)
        self.graph.open(self.path, create=self.create)

    def tearDown(self):
        self.graph.destroy(self.path)
        self.graph.close()

    def get_context(self, identifier):
        assert isinstance(identifier, URIRef) or isinstance(identifier, BNode), type(identifier)
        return Graph(store=self.graph.store, identifier=identifier, namespace_manager=self)

    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.add((tarek, likes, pizza))
        graph.add((tarek, likes, cheese))
        graph.add((michel, likes, pizza))
        graph.add((michel, likes, cheese))
        graph.add((bob, likes, cheese))
        graph.add((bob, hates, pizza))
        graph.add((bob, hates, michel))

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.remove((tarek, likes, pizza))
        graph.remove((tarek, likes, cheese))
        graph.remove((michel, likes, pizza))
        graph.remove((michel, likes, cheese))
        graph.remove((bob, likes, cheese))
        graph.remove((bob, hates, pizza))
        graph.remove((bob, hates, michel))

    def addStuffInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)

        # add to default context
        self.graph.add(triple)
        # add to context 1
        graph = Graph(self.graph.store, c1)
        graph.add(triple)
        # add to context 2
        graph = Graph(self.graph.store, c2)
        graph.add(triple)

    def testConjunction(self):
        self.addStuffInMultipleContexts()
        triple = (self.pizza, self.likes, self.pizza)
        # add to context 1
        graph = Graph(self.graph.store, self.c1)
        graph.add(triple)

        self.assertEquals(len(graph), 2)
        self.assertEquals(len(self.graph), 2)

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
#.........这里部分代码省略.........
开发者ID:DarioGT,项目名称:rdflib-django,代码行数:103,代码来源:test_rdflib.py

示例8: testFormulaStore

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
def testFormulaStore(store="default", configString=None):
    g = ConjunctiveGraph(store=store)


    if configString:
        g.destroy(configString)
        g.open(configString)
    else: 
        g.open(mkdtemp(), create=True)

    g.parse(data=testN3, format="n3")
    print g.store
    try:
        for s,p,o in g.triples((None,implies,None)):
            formulaA = s
            formulaB = o

        assert type(formulaA)==QuotedGraph and type(formulaB)==QuotedGraph
        a = URIRef('http://test/a')
        b = URIRef('http://test/b')
        c = URIRef('http://test/c')
        d = URIRef('http://test/d')
        v = Variable('y')

        universe = ConjunctiveGraph(g.store)

        #test formula as terms
        assert len(list(universe.triples((formulaA,implies,formulaB))))==1

        #test variable as term and variable roundtrip
        assert len(list(formulaB.triples((None,None,v))))==1
        for s,p,o in formulaB.triples((None,d,None)):
            if o != c:
                assert isinstance(o,Variable)
                assert o == v
        s = list(universe.subjects(RDF.type, RDFS.Class))[0]
        assert isinstance(s,BNode)
        assert len(list(universe.triples((None,implies,None)))) == 1
        assert len(list(universe.triples((None,RDF.type,None)))) ==1
        assert len(list(formulaA.triples((None,RDF.type,None))))==1
        assert len(list(formulaA.triples((None,None,None))))==2
        assert len(list(formulaB.triples((None,None,None))))==2
        assert len(list(universe.triples((None,None,None))))==3
        assert len(list(formulaB.triples((None,URIRef('http://test/d'),None))))==2
        assert len(list(universe.triples((None,URIRef('http://test/d'),None))))==1

        #context tests
        #test contexts with triple argument
        assert len(list(universe.contexts((a,d,c))))==1

        #Remove test cases
        universe.remove((None,implies,None))
        assert len(list(universe.triples((None,implies,None))))==0
        assert len(list(formulaA.triples((None,None,None))))==2
        assert len(list(formulaB.triples((None,None,None))))==2

        formulaA.remove((None,b,None))
        assert len(list(formulaA.triples((None,None,None))))==1
        formulaA.remove((None,RDF.type,None))
        assert len(list(formulaA.triples((None,None,None))))==0

        universe.remove((None,RDF.type,RDFS.Class))


        #remove_context tests
        universe.remove_context(formulaB)
        assert len(list(universe.triples((None,RDF.type,None))))==0
        assert len(universe)==1
        assert len(formulaB)==0

        universe.remove((None,None,None))
        assert len(universe)==0

        g.close()
        g.store.destroy(configString)
    except:
        g.close()
        g.store.destroy(configString)
        raise
开发者ID:alexsdutton,项目名称:rdflib,代码行数:81,代码来源:test_graph_formula.py

示例9: rdf_all

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]

#.........这里部分代码省略.........
    
        graph.open(path, create=True)
    else:
        assert rt == VALID_STORE, "The underlying store is corrupt"


    # Now we'll add some triples to the graph & commit the changes
    
    graph.bind("gstudio", "http://gnowledge.org/")
    exclusion_fields = ["id", "rght", "node_ptr_id", "image", "lft", "_state", "_altnames_cache", "_tags_cache", "nid_ptr_id", "_mptt_cached_fields"]

    for node in NID.objects.all():
    	    node_dict=node.ref.__dict__
    	    node_type = node.reftype
            try:       
            
           	 if (node_type=='Gbobject'):
    	    		node=Gbobject.objects.get(title=node)
    		
    	    	 elif (node_type=='None'):
    			node=Gbobject.objects.get(title=node)
    		 
            	 elif (node_type=='Processes'):
    			node=Gbobject.objects.get(title=node)
    			 
            	 elif (node_type=='System'):
    			node=Gbobject.objects.get(title=node)
    			rdflib=link(node)
			url_addr=link1(node)
                	a=fstore_dump(url_addr) 
            	 elif (node_type=='Objecttype'):
    			node=Objecttype.objects.get(title=node)
    			
    	    	 elif (node_type=='Attributetype'):
    			node=Attributetype.objects.get(title=node)
    	        	 
    	    	 elif (node_type=='Complement'):
    			node=Complement.objects.get(title=node)
    			
            	 elif (node_type=='Union'):
    	   		node=Union.objects.get(title=node)
    			 
            	 elif (node_type=='Intersection'):
    			node=Intersection.objects.get(title=node)
    	
            	 elif (node_type=='Expression'):
    			node=Expression.objects.get(title=node)
    		
            	 elif (node_type=='Processtype'):
    			node=Processtype.objects.get(title=node)
    		 
            	 elif (node_type=='Systemtype'):
    	 		node=Systemtype.objects.get(title=node)
    			
            	 elif (node_type=='AttributeSpecification'):
    			node=AttributeSpecification.objects.get(title=node)
    			
            	 elif (node_type=='RelationSpecification'):
    			node=RelationSpecification.objects.get(title=node)
    		 rdflib=link(node) 	 
                 url_addr=link1(node)
                 a=fstore_dump(url_addr) 
            	 if(node_type=='Attribute'):
    			node=Attribute.objects.get(title=node)
    			rdflib = Namespace('http://sbox.gnowledge.org/gstudio/')
              	
            	 elif(node_type=='Relationtype' ):
    			node=Relationtype.objects.get(title=node)
    			rdflib = Namespace('http://sbox.gnowledge.org/gstudio/')
                
    	    	 elif(node_type=='Metatype'):
    			node=Metatype.objects.get(title=node)
    			rdflib = Namespace('http://sbox.gnowledge.org/gstudio/')
                 url_addr='http://sbox.gnowledge.org/gstudio/'
                 a=fstore_dump(url_addr) 
            except:
            	if(node_type=='Attribute'):
                	rdflib= Namespace('http://sbox.gnowledge.org/gstudio/')
    
            	if(node_type=='Relationtype' ):
                	rdflib= Namespace('http://sbox.gnowledge.org/gstudio/')
                    
            	if(node_type=='Metatype'):
                	rdflib= Namespace('http://sbox.gnowledge.org/gstudio/')
            	
           
    subject=str(node_dict['id'])
    for key in node_dict:
        if key not in exclusion_fields:
           predicate=str(key)
           pobject=str(node_dict[predicate])
           graph.add((rdflib[subject], rdflib[predicate], Literal(pobject)))                        
        
    rdf_code=graph.serialize(format=notation)
               #path to store the rdf in a file
    
    #x = os.path.join(os.path.dirname(__file__), 'rdffiles.rdf')
    
    graph.commit()
    graph.close()
开发者ID:Big-Data,项目名称:gnowsys-studio,代码行数:104,代码来源:4store_rdf_import.py

示例10: Graph

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
import rdflib
from rdflib.graph import ConjunctiveGraph as Graph
#from rdflib.graph import Graph

configString = "/tmp/rdfstore12"

graph = Graph(store="KyotoCabinet")
print graph.store
path = configString
rt = graph.open(path, create=False)

print "Triples in graph: ", len(graph)
print "first 20 are as follows:"
i=20
for subj, pred, obj in graph:
    print(subj, pred, obj)
    i-=1
    if i==0:
	break


graph.close()
开发者ID:eugeneai,项目名称:aquarium,代码行数:24,代码来源:readRDF.py

示例11: TestKyotoCabinetConjunctiveGraphCore

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
class TestKyotoCabinetConjunctiveGraphCore(unittest.TestCase):
    def setUp(self):
        store = "KyotoCabinet"
        self.graph = ConjunctiveGraph(store=store)
        self.path = configString
        self.graph.open(self.path, create=True)

    def tearDown(self):
        self.graph.destroy(self.path)
        try:
            self.graph.close()
        except:
            pass
        if getattr(self, "path", False) and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    for f in os.listdir(self.path):
                        os.unlink(self.path + "/" + f)
                    os.rmdir(self.path)
                elif len(self.path.split(":")) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)

    def test_namespaces(self):
        self.graph.bind("dc", "http://http://purl.org/dc/elements/1.1/")
        self.graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
        self.assert_(len(list(self.graph.namespaces())) == 5)
        self.assert_(("foaf", rdflib.term.URIRef(u"http://xmlns.com/foaf/0.1/")) in list(self.graph.namespaces()))

    def test_play_journal(self):
        self.assertRaises(NotImplementedError, self.graph.store.play_journal, {"graph": self.graph})

    def test_readable_index(self):
        print(readable_index(111))

    def test_triples_context_reset(self):
        michel = rdflib.URIRef(u"michel")
        likes = rdflib.URIRef(u"likes")
        pizza = rdflib.URIRef(u"pizza")
        cheese = rdflib.URIRef(u"cheese")
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.commit()
        ntriples = self.graph.triples((None, None, None), context=self.graph.store)
        self.assert_(len(list(ntriples)) == 2)

    def test_remove_context_reset(self):
        michel = rdflib.URIRef(u"michel")
        likes = rdflib.URIRef(u"likes")
        pizza = rdflib.URIRef(u"pizza")
        cheese = rdflib.URIRef(u"cheese")
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.commit()
        self.graph.store.remove((michel, likes, cheese), self.graph.store)
        self.graph.commit()
        self.assert_(len(list(self.graph.triples((None, None, None), context=self.graph.store))) == 1)

    def test_remove_db_exception(self):
        michel = rdflib.URIRef(u"michel")
        likes = rdflib.URIRef(u"likes")
        pizza = rdflib.URIRef(u"pizza")
        cheese = rdflib.URIRef(u"cheese")
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.commit()
        self.graph.store.__len__(context=self.graph.store)
        self.assert_(len(list(self.graph.triples((None, None, None), context=self.graph.store))) == 2)
开发者ID:pebbie,项目名称:rdflib-kyotocabinet,代码行数:71,代码来源:test_corekc.py

示例12: ConjunctiveGraph

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
#!/usr/bin/env python

from rdflib.graph import ConjunctiveGraph

# Test basic SPARQL aggregation of the RDFa data
# see also http://identi.ca/notice/17728953 http://identi.ca/notice/17729227

g = ConjunctiveGraph("Sleepycat")
g.open("store", create=True)
g.parse("http://inkdroid.org/journal/network", format='rdfa', lax=True)
#g.parse("http://danbri.org/words/network", format='rdfa', lax=True)
g.parse("http://danbri.org/words/2009/12/29/523", format='rdfa', lax=True)
g.parse("http://melvincarvalho.com/blog/installed-f2f-plugin/", format='rdfa', lax=True)

q1="""PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    SELECT ?src1 ?src2 ?x 
    WHERE {
        GRAPH ?src1 { ?gr1 foaf:member [ foaf:openid ?x ] }
        GRAPH ?src2 { ?gr2 foaf:member [ foaf:openid ?x ] }
        FILTER ( ?src1 != ?src2 )
    }"""

for src1, src2, x in  g.query(q1):
    print src1, src2, x

g.close() 
开发者ID:foaf,项目名称:foaftown,代码行数:28,代码来源:crawler.py

示例13: ContextTestCase

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]
class ContextTestCase(unittest.TestCase):
    #store = 'Memory'
    store = 'default'
    slow = True

    def setUp(self):
        self.graph = ConjunctiveGraph(store=self.store)
        if self.store == "MySQL":
            from mysql import configString
            from rdflib.store.MySQL import MySQL
            path=configString
            MySQL().destroy(path)
        else:
            path = a_tmp_dir = mkdtemp()
        self.graph.open(path, create=True)
        self.michel = URIRef(u'michel')
        self.tarek = URIRef(u'tarek')
        self.bob = URIRef(u'bob')
        self.likes = URIRef(u'likes')
        self.hates = URIRef(u'hates')
        self.pizza = URIRef(u'pizza')
        self.cheese = URIRef(u'cheese')

        self.c1 = URIRef(u'context-1')
        self.c2 = URIRef(u'context-2')

        # delete the graph for each test!
        self.graph.remove((None, None, None))

    def tearDown(self):
        self.graph.close()

    def get_context(self, identifier):
        assert isinstance(identifier, URIRef) or \
               isinstance(identifier, BNode), type(identifier)
        return Graph(store=self.graph.store, identifier=identifier,
                         namespace_manager=self)
    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.add((tarek, likes, pizza))
        graph.add((tarek, likes, cheese))
        graph.add((michel, likes, pizza))
        graph.add((michel, likes, cheese))
        graph.add((bob, likes, cheese))
        graph.add((bob, hates, pizza))
        graph.add((bob, hates, michel)) # gasp!

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.remove((tarek, likes, pizza))
        graph.remove((tarek, likes, cheese))
        graph.remove((michel, likes, pizza))
        graph.remove((michel, likes, cheese))
        graph.remove((bob, likes, cheese))
        graph.remove((bob, hates, pizza))
        graph.remove((bob, hates, michel)) # gasp!

    def addStuffInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek) # revenge!

        # add to default context
        self.graph.add(triple)
        # add to context 1
        graph = Graph(self.graph.store, c1)
        graph.add(triple)
        # add to context 2
        graph = Graph(self.graph.store, c2)
        graph.add(triple)

    def testConjunction(self):
        self.addStuffInMultipleContexts()
        triple = (self.pizza, self.likes, self.pizza)
        # add to context 1
        graph = Graph(self.graph.store, self.c1)
        graph.add(triple)
        self.assertEquals(len(self.graph), len(graph))

    def testAdd(self):
        self.addStuff()

#.........这里部分代码省略.........
开发者ID:alcides,项目名称:rdflib,代码行数:103,代码来源:test_context.py

示例14: __init__

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]

#.........这里部分代码省略.........
            return None


    def defaultEnding(self, content_type=None, language=None):
        cts = { "application/rdf+xml": ".rdf", "application/xhtml+xml": ".xhtml", "text/html": ".html", None: "" }
        if content_type:
            typeendings = list(self.confGraph.objects(URIRef("http://purl.org/NET/mediatypes/" + content_type), semp.defaultExtension))
            if len(typeendings) > 1:
                raise SemPipeException("ambiguous extension for content-type {} in confGraph.".format(content_type))
            elif len(typeendings) < 1:
                raise SemPipeException("No extension for content-type {} found".format(content_type))
            else:
                typeending = typeendings[0]
        else:
            typeending = ""
        return ("." + language if language else "") + "." + typeending

    def write_htaccess(self):
        """Writes all required .htaccess files."""

        # First generate the directives for each resource
        filesinfo = [];
        resources = self.resources
        for resource in resources:
            info = [];
            filesinfo.append((resource, info));
            if self.typemap(resource) is not None:
                info.append("SetHandler type-map\n")

        # Generate the .htaccess files
        htaccessfiles = dict()
        for resource, info in filter(lambda x: x[1], filesinfo):
            directory, filename = resource.rsplit("/", 1)
            ht = htaccessfiles.setdefault(directory, [])
            ht.append('<Files "{}">\n'.format(filename))
            ht += info
            ht.append('</Files>\n')

        for directory, ht in htaccessfiles.items():
            print("Writing a .htaccess in {}".format(directory), file=sys.stderr)
            filename = self.hostedSpace(resource).htaccess
            self.write(directory + "/" + filename, "".join(ht).encode("UTF-8"))

    def publish(self):
        import getpass
        import subprocess

        """Walks through HostedSpaces and upload the respective files
        from the build diretory.

        (Instead we should walk through the build directory. Will be
        changed later.)"""

        hostedSpacesQuery = """
        SELECT ?space ?method ?command ?invocation
        WHERE {
            ?space a semp:HostedSpace .
            ?space semp:publishMethod ?method .
            ?method semp:command ?command .
            ?method semp:invocation ?invocation .
        }"""
        askForQuery = """
        SELECT ?variable
        WHERE {
            { ?method semp:askFor ?variable . }
            UNION
            { ?method semp:askForHidden ?variable . }
        }""" 
        #?hidden
        #{ ?method semp:askFor ?variable . }
        #UNION
        #{ ?method semp:askForHidden ?variable .
        #  BIND ("true"^^xsd:boolean as ?hidden) }
        for spaceRow in self.confGraph.query(hostedSpacesQuery, initNs={"semp": semp}).bindings:
            space = spaceRow[Variable("?space")]
            method = spaceRow[Variable("?method")]
            answers = dict()
            for question in self.confGraph.query(askForQuery, initNs={"semp": semp}, initBindings={"method": method}).bindings:
                answers[question[Variable("?variable")]] = getpass.getpass("{} for method {}".format(question[Variable("?variable")], method))
            spacedir = self.buildLocation(space)
            command = []
            for arg in Collection(self.confGraph, spaceRow[Variable("command")]):
                command.append(str(arg).format("",fileurl2path(spacedir),str(space),**answers))
            print("Running {}".format(command[0]), file=sys.stderr)
            subprocess.call(command)

    @property
    def resources(self):
        return self.confGraph.subjects(rdf.type, semp.Resource)

    def commit(self):
        self.g.commit()
        if self.storePath:
            self.g.serialize(destination=self.storePath+"/store.nq", format='nquads', encoding='UTF-8')

    def serialize(self):
        return self.g.serialize()

    def close(self):
        self.g.close()
开发者ID:uholzer,项目名称:sempipe,代码行数:104,代码来源:__init__.py

示例15: rdf_description

# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import close [as 别名]

#.........这里部分代码省略.........
    	"""
	name='student'
    	valid_formats = ["xml", "n3", "ntriples", "trix"]
    	default_graph_uri = "http://gstudio.gnowledge.org/rdfstore"
   	# default_graph_uri = "http://example.com/"
    	configString = "/var/tmp/rdfstore"

    	# Get the Sleepycat plugin.
    	store = plugin.get('IOMemory', Store)('rdfstore')
   


    	# Open previously created store, or create it if it doesn't exist yet
    	graph = Graph(store="IOMemory",
              	identifier = URIRef(default_graph_uri))
    	path = mkdtemp()
    	rt = graph.open(path, create=False)
    	if rt == NO_STORE:
    #There is no underlying Sleepycat infrastructure, create it
        	graph.open(path, create=True)
    	else:
        	assert rt == VALID_STORE, "The underlying store is corrupt"


    # Now we'll add some triples to the graph & commit the changes
   # rdflib = Namespace('http://sbox.gnowledge.org/gstudio/')
    	graph.bind("gstudio", "http://gnowledge.org/")
    	exclusion_fields = ["id", "rght", "node_ptr_id", "image", "lft", "_state", "_altnames_cache", "_tags_cache", "nid_ptr_id", "_mptt_cached_fields"]
    	node_type=get_nodetype()
    	if (node_type=='gbobject'):
        	node=Gbobject.objects.get(title=name)
    	elif (node_type=='objecttype'):
       		node=Objecttype.objects.get(title=name)
  	elif (node_type=='metatype'):
        	node=Metatype.objects.get(title=name)
    	elif (node_type=='attributetype'):
       		node=Attributetype.objects.get(title=name)
   	elif (node_type=='relationtype'):
       		node=Relationtype.objects.get(title=name)
  	elif (node_type=='attribute'):
        	node=Attribute.objects.get(title=name)
    	elif (node_type=='complement'):
        	node=Complement.objects.get(title=name)
    	elif (node_type=='union'):
        	node=Union.objects.get(title=name)
    	elif (node_type=='intersection'):
        	node=Intersection.objects.get(title=name)
    	elif (node_type=='expression'):
        	node=Expression.objects.get(title=name)
    	elif (node_type=='processtype'):
        	node=Processtype.objects.get(title=name)
    	elif (node_type=='systemtype'):
        	node=Systemtype.objects.get(title=name)
   
   
    
   
    
    	node_url=node.get_absolute_url()
    	site_add= node.sites.all() 
    	a = site_add[0] 
    	host_name =a.name
    #host_name=name
    	link='http://'
    #Concatenating the above variables will give the url address.

    	url_add=link+host_name+node_url
    	rdflib = Namespace(url_add)
 # node=Objecttype.objects.get(title=name)

    	node_dict=node.__dict__

    	subject=str(node_dict['id'])
    	for key in node_dict:
        	if key not in exclusion_fields:
            		predicate=str(key)
            		pobject=str(node_dict[predicate])
            		graph.add((rdflib[subject], rdflib[predicate], Literal(pobject)))

     
    	rdf_code=graph.serialize(format=notation)

   

    


    #graph = rdflib.Graph("IOMemory")
    #graph.open("store", create=True)
    #graph.parse(rdf_code)

    # print out all the triples in the graph
   # for subject, predicate, object in graph:
      #  print subject, predicate, object
   # store.add(self,(subject, predicate, object),context)
     
     
    	graph.commit()
    	print rdf_code
    	graph.close()
开发者ID:Big-Data,项目名称:gnowsys-studio,代码行数:104,代码来源:generate_rdf_xml.py


注:本文中的rdflib.graph.ConjunctiveGraph.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。