Package SPARQLWrapper :: Module SmartWrapper
[hide private]
[frames] | no frames]

Source Code for Module SPARQLWrapper.SmartWrapper

  1  # -*- coding: utf-8 -*- 
  2   
  3  """ 
  4  @see: U{SPARQL Specification<http://www.w3.org/TR/rdf-sparql-query/>} 
  5  @authors: U{Ivan Herman<http://www.ivan-herman.net>}, U{Sergio Fernández<http://www.wikier.org>}, U{Carlos Tejo Alonso<http://www.dayures.net>} 
  6  @organization: U{World Wide Web Consortium<http://www.w3.org>} and U{Foundation CTIC<http://www.fundacionctic.org/>}. 
  7  @license: U{W3C® SOFTWARE NOTICE AND LICENSE<href="http://www.w3.org/Consortium/Legal/copyright-software">} 
  8  @requires: U{RDFLib<http://rdflib.net>} package. 
  9  """ 
 10   
 11  import SPARQLWrapper 
 12  from SPARQLWrapper.Wrapper import JSON, SELECT 
 13  import urllib2 
 14  from types import * 
 15   
 16   
 17  ###################################################################################### 
 18   
19 -class Value(object):
20 """ 21 Class encapsulating a single binding for a variable. 22 23 @cvar URI: the string denoting a URI variable 24 @cvar Literal: the string denoting a Literal variable 25 @cvar TypedLiteral: the string denoting a typed literal variable 26 @cvar BNODE: the string denoting a blank node variable 27 28 @ivar variable: The original variable, stored for an easier reference 29 @type variable: string 30 @ivar value: Value of the binding 31 @type value: string 32 @ivar type: Type of the binding 33 @type type: string; one of L{Value.URI}, L{Value.Literal}, L{Value.TypedLiteral}, or L{Value.BNODE} 34 @ivar lang: Language tag of the binding, or C{None} if not set 35 @type lang: string 36 @ivar datatype: Datatype of the binding, or C{None} if not set 37 @type datatype: string (URI) 38 """ 39 URI = "uri" 40 Literal = "literal" 41 TypedLiteral = "typed-literal" 42 BNODE = "bnode" 43
44 - def __init__(self,variable,binding) :
45 """ 46 @param variable: the variable for that binding. Stored for an easier reference 47 @param binding: the binding dictionary part of the return result for a specific binding 48 """ 49 self.variable = variable 50 self.value = binding['value'] 51 self.type = binding['type'] 52 self.lang = None 53 self.datatype = None 54 try : 55 self.lang = binding['xml:lang'] 56 except : 57 # no lang is set 58 pass 59 try : 60 self.datatype = binding['datatype'] 61 except : 62 pass
63 64 ###################################################################################### 65 66
67 -class Bindings(object):
68 """ 69 Class encapsulating one query result, based on the JSON return format. It decodes the 70 return values to make it a bit more usable for a standard usage. The class consumes the 71 return value and instantiates a number of attributes that can be consulted directly. See 72 the list of variables. 73 74 The U{Serializing SPARQL Query Results in JSON<http://www.w3.org/TR/rdf-sparql-json-res/>} explains the details of the 75 JSON return structures. Very succintly: the return data has "bindings", which means a list of dictionaries. Each 76 dictionary is a possible binding of the SELECT variables to L{Value} instances. This structure is made a bit 77 more usable by this class. 78 79 @ivar fullResult: The original dictionary of the results, stored for an easier reference 80 @ivar head: Header part of the return, see the JSON return format document for details 81 @ivar variables: List of unbounds (variables) of the original query. It is an array of strings. None in the case of an ASK query 82 @ivar bindings: The final bindings: array of dictionaries, mapping variables to L{Value} instances. 83 (If unbound, then no value is set in the dictionary; that can be easily checked with 84 C{var in res.bindings[..]}, for example.) 85 @ivar askResult: by default, set to False; in case of an ASK query, the result of the query 86 @type askResult: Boolean 87 """
88 - def __init__(self,retval) :
89 """ 90 @param retval: the query result, instance of a L{Wrapper.QueryResult} 91 """ 92 self.fullResult = retval._convertJSON() 93 self.head = self.fullResult['head'] 94 self.variables = None 95 try : 96 self.variables = self.fullResult['head']['vars'] 97 except : 98 pass 99 100 self.bindings = [] 101 try : 102 for b in self.fullResult['results']['bindings'] : 103 # this is a single binding. It is a dictionary per variable; each value is a dictionary again that has to be 104 # converted into a Value instance 105 newBind = {} 106 for key in self.variables : 107 if key in b : 108 # there is a real binding for this key 109 newBind[key] = Value(key,b[key]) 110 self.bindings.append(newBind) 111 except : 112 pass 113 114 self.askResult = False 115 try : 116 self.askResult = self.fullResult["boolean"] 117 except : 118 pass
119
120 - def getValues(self,key) :
121 """A shorthand for the retrieval of all bindings for a single key. It is 122 equivalent to "C{[b[key] for b in self[key]]}" 123 @param key: possible variable 124 @return: list of L{Value} instances 125 """ 126 try : 127 return [b[key] for b in self[key]] 128 except : 129 return []
130
131 - def __contains__(self,key) :
132 """Emulation of the "C{key in obj}" operator. Key can be a string for a variable or an array/tuple 133 of strings. 134 135 If C{key} is a variable, the return value is C{True} if there is at least one binding where C{key} is 136 bound. If C{key} is an array or tuple, the return value is C{True} if there is at least one binding 137 where I{all} variables in C{key} are bound. 138 139 @param key: possible variable, or array/tuple of variables 140 @return: whether there is a binding of the variable in the return 141 @rtype: Boolean 142 """ 143 if len(self.bindings) == 0 : return False 144 if type(key) is list or type(key) is tuple: 145 # check first whether they are all really variables 146 if False in [ k in self.variables for k in key ]: return False 147 for b in self.bindings : 148 # try to find a binding where all key elements are present 149 if False in [ k in b for k in key ] : 150 # this is not a binding for the key combination, move on... 151 continue 152 else : 153 # yep, this one is good! 154 return True 155 return False 156 else : 157 if key not in self.variables : return False 158 for b in self.bindings : 159 if key in b : return True 160 return False
161
162 - def __getitem__(self,key) :
163 """Emulation of the C{obj[key]} operator. Slice notation is also available. 164 The goal is to choose the right bindings among the available ones. The return values are always 165 arrays of bindings, ie, arrays of dictionaries mapping variable keys to L{Value} instances. 166 The different value settings mean the followings: 167 168 - C{obj[key]} returns the bindings where C{key} has a valid value 169 - C{obj[key1,key2,...]} returns the bindings where I{all} C{key1,key2,...} have valid values 170 - C{obj[(key1,key2,...):(nkey1,nkey2,...)]} returns the bindings where all C{key1,key2,...} have 171 valid values and I{none} of the C{nkey1,nkey2,...} have valid values 172 - C{obj[:(nkey1,nkey2,...)]} returns the bindings where I{none} of the C{nkey1,nkey2,...} have valid values 173 174 In all cases complete bindings are returned, ie, the values for other variables, not present among 175 the keys in the call, may or may not be present depending on the query results. 176 177 @param key: possible variable or array/tuple of keys with possible slice notation 178 @return: list of bindings 179 @rtype: array of variable -> L{Value} dictionaries 180 """ 181 def _checkKeys(keys) : 182 if len(keys) == 0 : return False 183 for k in keys : 184 if not isinstance(k, basestring) or not k in self.variables: return False 185 return True
186 187 def _nonSliceCase(key) : 188 if isinstance(key, basestring) and key != "" and key in self.variables : 189 # unicode or string: 190 return [key] 191 elif type(key) is list or type(key) is tuple: 192 if _checkKeys(key) : 193 return key 194 return False
195 196 # The arguments should be reduced to arrays of variables, ie, unicode strings 197 yes_keys = [] 198 no_keys = [] 199 if type(key) is slice : 200 # Note: None for start or stop is all right 201 if key.start : 202 yes_keys = _nonSliceCase(key.start) 203 if not yes_keys: raise TypeError 204 if key.stop : 205 no_keys = _nonSliceCase(key.stop) 206 if not no_keys: raise TypeError 207 else : 208 yes_keys = _nonSliceCase(key) 209 210 # got it right, now get the right binding line with the constraints 211 retval = [] 212 for b in self.bindings : 213 # first check whether the 'yes' part is all there: 214 if False in [k in b for k in yes_keys] : continue 215 if True in [k in b for k in no_keys] : continue 216 # if we got that far, we shouild be all right! 217 retval.append(b) 218 # if retval is of zero length, no hit; an exception should be raised to stay within the python style 219 if len(retval) == 0 : 220 raise IndexError 221 return retval 222
223 - def convert(self) :
224 """This is just a convenience method, returns C{self}. 225 226 Although C{Binding} is not a subclass of L{QueryResult<SPARQLWrapper.Wrapper.QueryResult>}, it is returned as a result by 227 L{SPARQLWrapper2.query}, just like L{QueryResult<SPARQLWrapper.Wrapper.QueryResult>} is returned by 228 L{SPARQLWrapper.SPARQLWrapper.query}. Consequently, 229 having an empty C{convert} method to imitate L{QueryResult's convert method<SPARQLWrapper.Wrapper.QueryResult.convert>} may avoid unnecessary problems. 230 """ 231 return self
232 233 ############################################################################################################## 234 235
236 -class SPARQLWrapper2(SPARQLWrapper.SPARQLWrapper):
237 """Subclass of L{Wrapper<SPARQLWrapper.SPARQLWrapper>} that works with a JSON SELECT return result only. The query result 238 is automatically set to a L{Bindings} instance. Makes the average query processing a bit simpler..."""
239 - def __init__(self, baseURI, defaultGraph=None):
240 """ 241 Class encapsulating a full SPARQL call. In contrast to the L{SPARQLWrapper<SPARQLWrapper.SPARQLWrapper>} superclass, the return format 242 cannot be set (it is defaulted to L{JSON<Wrapper.JSON>}). 243 @param baseURI: string of the SPARQL endpoint's URI 244 @type baseURI: string 245 @keyword defaultGraph: URI for the default graph. Default is None, can be set via an explicit call, too 246 @type defaultGraph: string 247 """ 248 super(SPARQLWrapper2, self).__init__(baseURI, returnFormat=JSON, defaultGraph=defaultGraph)
249
250 - def setReturnFormat(self, format):
251 """Set the return format (overriding the L{inherited method<SPARQLWrapper.SPARQLWrapper.setReturnFormat>}). 252 This method does nothing; this class instance should work with JSON only. The method is defined 253 just to avoid possible errors by erronously setting the return format. 254 When using this class, the user can safely ignore this call. 255 @param format: return format 256 """ 257 pass
258
259 - def query(self):
260 """ 261 Execute the query and do an automatic conversion. 262 263 Exceptions can be raised if either the URI is wrong or the HTTP sends back an error. 264 The usual urllib2 exceptions are raised, which cover possible SPARQL errors, too. 265 266 If the query type is I{not} SELECT, the method falls back to the 267 L{corresponding method in the superclass<SPARQLWrapper.query>}. 268 269 @return: query result 270 @rtype: L{Bindings} instance 271 """ 272 res = super(SPARQLWrapper2, self).query() 273 274 if self.queryType == SELECT: 275 return Bindings(res) 276 else: 277 return res
278
279 - def queryAndConvert(self):
280 """This is here to override the inherited method; it is equivalent to L{query}. 281 282 If the query type is I{not} SELECT, the method falls back to the 283 L{corresponding method in the superclass<SPARQLWrapper.queryAndConvert>}. 284 285 @return: the converted query result. 286 """ 287 if self.queryType == SELECT: 288 return self.query() 289 else: 290 return super(SPARQLWrapper2, self).queryAndConvert()
291