/
sparql_connect.py
50 lines (43 loc) · 1.76 KB
/
sparql_connect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from SPARQLWrapper import SPARQLWrapper, JSON, XML, N3, RDF
DEBUG = False
"""This class is built on the sparql wrapper which queries a sparql endpoint
The returned results are then parsed based on the content type returned """
#TODO: 1. The graph should be initialized onlu once since we will be workin
# on a single graph
class VirtuosoConnect:
"""This function executes a select sparql query and returns a wrapper object
The wrapper object can later be converted to get any format of result needed"""
def select(self, query):
prefix = """PREFIX sioc: <http://rdfs.org/sioc/ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX push: <http://push.deri.ie/smob/>
"""
query = prefix + query
sparql = SPARQLWrapper("http://localhost:8890/sparql")
sparql.setQuery(query)
logging.debug('Query: %r', query)
uris = self.returnJson(sparql)
logging.debug('uris: %r', uris)
return uris
"""This function takes in a insert statment and returns
whether it was executed fine or not"""
def insert(self, insQuery):
print insQuery
sparql = SPARQLWrapper("http://localhost:8890/sparql")
sparql.setQuery("""
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
INSERT DATA
INTO <http://localhost:8890/DAV/home/smob>
{ <s> <p> <q> }
""")
results=sparql.query().convert()
def returnJson(self, wrapper):
uris = []
wrapper.setReturnFormat(JSON)
results = wrapper.query().convert()
for result in results["results"]["bindings"]:
uris.append(result["callback"]["value"])
return uris