blob: fe873e9cc1361d9e73235603e0a5821927b2774c (
plain)
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
|
'''
Created on 25 Aug 2011
@author: cgueret
'''
# python import
import httplib, urllib, cjson
# rdflib import
from rdflib_ import URIRef, Literal
class SPARQL(object):
def __init__(self, url):
self._url = url
def execute_select(self, query):
results = []
params = {'query': query, 'format' : 'json'}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
try:
# Open the connection
conn = httplib.HTTPConnection(self._url)
conn.request("POST", "/sparql", urllib.urlencode(params), headers=headers)
# Get the results
response = conn.getresponse()
r = cjson.decode(response.read(), all_unicode=False)
# Recode them
for entry in r['results']['bindings']:
result = {}
for (name,data) in entry.iteritems():
value = Literal(data['value'])
if data['type']=='uri':
value = URIRef(data['value'])
result[name] = value
results.append(result)
conn.close()
except:
pass
# returns select results or empty list
return results
|