#!/usr/local/bin/python # Testing: # Browsers: # Tested successfully with IE, Firefox on Windows and Ubuntu. Doesn't # work with Google chrome. # Pass query to SPARQL endpoint, return result as HTML following Excel # mimetype so that client will load it into a spreadsheet app. # Bob DuCharme 2008-10-27 No warantee expressed or implied. import sys sys.path.append('/usr/home/bobd/lib/python/') from SPARQLWrapper import SPARQLWrapper, JSON import cgi import urllib form = cgi.FieldStorage() queryString = str(form.getvalue('query')) endpoint = form.getvalue('endpoint') # for testing: #queryString ="SELECT ?red ?green ?blue WHERE { ?red ?green ?blue .} LIMIT 3" #queryString = "SELECT DISTINCT ?p WHERE {?s ?p ?o}" #endpoint = "http://dbpedia.org/sparql" prefixDeclarations = """ PREFIX owl: PREFIX xsd: PREFIX rdfs: PREFIX rdf: PREFIX foaf: PREFIX dc: PREFIX : PREFIX dbpedia2: PREFIX dbpedia: PREFIX skos: """ if queryString == None: queryString = "" # empty string to prevent type mismatch in next line queryString = prefixDeclarations + queryString if endpoint == None: endpoint = "http://dbpedia.org/sparql" sparql = SPARQLWrapper(endpoint) sparql.setQuery(queryString) sparql.setReturnFormat(JSON) try: ret = sparql.query() results = ret.convert() # Number of columns in spreadsheet (i.e. number of variables in query) cols = len(results["head"]["vars"]) # We're really creating an HTML table, but with this content # type, a client will open it with a spreadsheet app. print "Content-type: application/vnd.ms-excel\n" #print "Content-type: text/html\n" print "" print "" print "" # Print the variable names as the spreadsheet's first row print "" for i in range (0, cols): print "" print "" # Print the rows of the spreadsheet. Variable names needed # as keys into dictionary for each row. for v in results["results"]["bindings"]: print "" for i in range (0, cols): value=v[results["head"]["vars"][i]]["value"] value = value.encode('utf-8') print "" print "" print "
" + results["head"]["vars"][i] + "
" + value + "
" #print "" except Exception, errorMsg: results = str(errorMsg) print "Content-type: text/html\n\n" print "

Problem requesting data from SPARQL endpoint: " print results + "

" print "" print ""