-
Notifications
You must be signed in to change notification settings - Fork 3
/
pysesame.py
executable file
·234 lines (214 loc) · 7.73 KB
/
pysesame.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
from urllib import quote_plus, urlencode, quote
import urllib2, types
from simplejson import loads
SPJSON='application/sparql-results+json'
SPXML='application/sparql-results+xml'
SPCXML='application/rdf+xml'
SPCN3='text/rdf+n3'
SPATXT='text/boolean'
SPOC={
's':'subj',
'o':'obj',
'p':'pred',
'c':'context'
}
class connection:
def __init__(self,url):
self.baseurl=url
self.sparql_prefix=""
def addnamespace(self,id,ns):
self.sparql_prefix+='PREFIX %s:<%s>\n' % (id,ns)
def __getsparql__(self, atype, method, uri=None):
"""Updated to support both POST and get styles. If POST, the posting
uri must be supplied. If GET method is entire URI, if POST its the
query string
"""
#print method,uri
if uri!=None:
req=urllib2.Request(self.baseurl+uri)
else:
req=urllib2.Request(self.baseurl+method)
req.add_header('Accept', atype)
#req.add_header('Accept', 'application/sparql-results+json')
#NEEDED to SET above to get sensible results.
#req.add_header('Accept', 'application/rdf+xml')
#req.add_header('Accept', 'application/sparql-results+xml')
if uri !=None:
req.add_data(method)
req.add_header('Content-Type','application/x-www-form-urlencoded')
#print "INPUTDATA", req.get_data()
try:
sock=urllib2.urlopen(req)
#print "INFO", sock.info()
data=sock.read()
#print "DATA", data
sock.close()
except urllib2.HTTPError, e:
print 'Code: ', e.code
except urllib2.URLError, e:
print 'Reason: ', e.reason
except:
import sys, traceback
data=""
print "ERROR", traceback.print_tb(sys.exc_info()[2])
#return [{'error':data}]
if atype != SPJSON:
print "ATYPE", atype
return data
try:
#print "LOADSDATA", data
result=loads(data)['results']['bindings']
return result
except:
import sys, traceback
print "ERRORX", traceback.print_tb(sys.exc_info()[2])
return [{'error':data}]
def use_repository(self,r):
self.repository=r
def query(self,q, atype=SPJSON):
print "LENGTH", len(self.sparql_prefix+q)
q='repositories/'+self.repository+'?query='+quote_plus(self.sparql_prefix+q)
#print "Q",q
return self.__getsparql__(atype, q)
def querypost(self, q, atype=SPJSON):
uri='repositories/'+self.repository
#print self.sparql_prefix
#print q
q='query='+quote_plus(self.sparql_prefix+q)
#print q
#q='query='+quote_plus(q)
#print "Q",q
return self.__getsparql__(atype, q, uri)
def construct_query(self,q):
q='repositories/'+self.repository+'?query='+quote_plus(self.sparql_prefix+q)
res=urllib2.urlopen(self.baseurl+q)
data=res.read()
res.close()
return data
def query_statements(self, qdict, atype=SPCXML):
"query statements in rep for subject, object, predicate, or context..spoc"
host=self.baseurl+'repositories/'+self.repository+'/statements'
#print 'HOST', host
#BUG we do not handle if qitem is a list yet
qlist=[]
for qtype, qitem in qdict.items():
if type(qitem)==types.ListType:#NOT SUPPORTED BY SESAME
for themem in qitem:
qlist.append(SPOC[qtype]+"="+quote_plus(themem))
else:
qlist.append(SPOC[qtype]+"="+quote_plus(qitem))
endpoint=host+"?"+'&'.join(qlist)
#print "ENDPOINT",endpoint
req=urllib2.Request(endpoint)
#accepting rdf/xml not ntriples
req.add_header('Accept', atype)
res=urllib2.urlopen(req)
#print "INFO", res.info()
readstuff=res.read()
res.close()
return readstuff
def get_in_context(self, context=None, atype=SPCXML):
host=self.baseurl+'repositories/'+self.repository+'/statements'
if context==None:
endpoint=host
else:
endpoint=host+"?"+'context='+quote_plus(context)
#print "ENDPOINT",endpoint
req=urllib2.Request(endpoint)
#accepting rdf/xml not ntriples
req.add_header('Accept', atype)
res=urllib2.urlopen(req)
#print "INFO", res.info()
readstuff=res.read()
res.close()
return readstuff
def deletedata(self, context=None):
#delete everything in a repository or in a specific context
host=self.baseurl+'repositories/'+self.repository+'/statements'
if context==None:
endpoint=host
else:
endpoint=host+"?"+'context='+quote_plus(context)
#print 'HOST', host , endpoint
req=urllib2.Request(endpoint)
req.get_method = lambda: 'DELETE'
try:
res=urllib2.urlopen(req)
except urllib2.HTTPError, e:
print 'Code: ', e.code
res=None
if e.code > 299:
print 'Error code: ', e.code
raise ValueError(e.code)
res.close()
return 0
#print "INFO", res.info()
res.close()
return 0
def postdata(self,data, context=None, method='POST'):
"POST/PUT a bunch of RDF statements into the repository"
#PUT replaces, rather than adds, either for whole rep, or for context
#/openrdf-sesame/repositories/mem-rdf/statements
host=self.baseurl+'repositories/'+self.repository+'/statements'
if context==None:
endpoint=host
elif type(context)==types.ListType:
qlist=["context="+ele for ele in context]
endpoint=host+"?"+'&'.join(qlist)
else:
endpoint=host+"?"+'context='+context
#print 'ENDPOINT', endpoint
req=urllib2.Request(endpoint)
if method=='PUT':#otherwise assume POST
req.get_method = lambda: 'PUT'
req.add_header('Content-Type', SPCXML)
req.add_data(data)
try:
res=urllib2.urlopen(req)
print res.info()
except urllib2.HTTPError, e:
print 'Code: ', e.code
res=None
if e.code > 299:
print 'Error code: ', e.code
raise ValueError(e.code)
res.close()
return 0
#print "INFO", res.info()
#readstuff=res.read()
res.close()
return 0
def postfile(self, thefile, context=None, method='POST'):
#print "FILE", thefile
fd=open(thefile)
data=fd.read()
fd.close()
#print "DATA"
#print data
#print "========================"
res=self.postdata(data, context, method)
return res
q1="""
SELECT ?costar ?movie WHERE {
?movie fb:film.film.starring fb:en.john_travolta .
?movie fb:film.film.starring ?costar .
filter (?costar != fb:en.john_travolta)
}
"""
q2="""
SELECT ?costar ?fn WHERE {?film fb:film.film.performances ?p1 .
?film dc:title ?fn .
?p1 fb:film.performance.actor ?a1 .
?a1 dc:title "John Malkovich".
?film fb:film.film.performances ?p2 .
?p2 fb:film.performance.actor ?a2 .
?a2 dc:title ?costar .}
"""
if __name__=='__main__':
c=connection('http://localhost:8081/openrdf-sesame/')
c.use_repository('testmovie')
c.addnamespace('fb','http://rdf.freebase.com/ns/')
c.addnamespace('dc','http://purl.org/dc/elements/1.1/')
res=c.query(q1)
for r in res:
print ">>",r