PageRenderTime 49ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/franziska/api/query.py

https://bitbucket.org/timgluz/franziska
Python | 245 lines | 236 code | 2 blank | 7 comment | 0 complexity | c54549aa9d218b431655f8898d233857 MD5 | raw file
  1. '''
  2. Query.py includes all type of queries, which AllegroGraph accepts
  3. '''
  4. import simplejson
  5. from mimetypes import mimetypes
  6. class Query(object):
  7. """
  8. base-class for Query-objects
  9. """
  10. __cmd__ = ""
  11. _response_type = None
  12. _content_type = None
  13. def __init__(self):
  14. self._field_map = {} #use this when allegro param and python names differ
  15. def build_headers(self):
  16. '''helps to build HTTP headers for query object'''
  17. headers = { "Accept": mimetypes[self._response_type],
  18. "Content-type": mimetypes[self._content_type]
  19. }
  20. return headers
  21. def to_dict(self,
  22. ignore_none = True,
  23. ignore_priv = True,
  24. ignore_callable = True):
  25. '''exports class as dict,
  26. by default skips items with None, and __privvar__
  27. '''
  28. def ignored(key, val, ignore_none, ignore_priv, ignore_callable):
  29. '''closure, that helps to filter out class members'''
  30. if ignore_priv and key.startswith("_"):
  31. return True
  32. elif ignore_none and val is None:
  33. return True
  34. elif ignore_callable and\
  35. (hasattr(val, "__call__")):
  36. return True
  37. else:
  38. return False
  39. items = {}
  40. for key,val in self.__dict__.items():
  41. if not ignored(key, val, ignore_none, ignore_priv, ignore_callable):
  42. if self._field_map.has_key(key):
  43. #map query fieldname with database's one
  44. key = self._field_map[key]
  45. items[str(key)] = str(val)
  46. return items
  47. def to_json(self, ignore_none = True):
  48. return simplejson.dumps(self.to_dict(ignore_none))
  49. class QueryResponse(object):
  50. """
  51. """
  52. def __init__(self):
  53. pass
  54. class RepoQuery(Query):
  55. '''
  56. Base class for all queries
  57. '''
  58. def __init__(self, query, query_lng,
  59. response_type,
  60. content_type = None,
  61. infer = False,
  62. context = None, named_context = None,
  63. default_graph_uri = None,
  64. named_graph_uri = None,
  65. limit = None,
  66. offset = None,
  67. variables = None, check_variables = False,
  68. default_graph_name = None,
  69. planner = None,
  70. save = None
  71. ):
  72. '''
  73. query - The query to be executed. The query may use the namespace
  74. prefixes defined for the user.
  75. queryLn - The language of the query. Can be sparql or prolog.
  76. Defaults to sparql.
  77. infer - A string that determines what kind of reasoning is used when
  78. executing the query. Default is false, no reasoning. Other options
  79. are rdfs++ (same as true), and restriction for
  80. hasValue as well as rdf++ reasoning.
  81. context - Can be passed zero or more times. Sets the graph name, or
  82. list of graph names, that will be used by this query (as in FROM).
  83. When no context is given, all graphs are used. The string null
  84. can be used to refer to the default graph of the store.
  85. namedContext - Also can be given multiple times. Behaves like context,
  86. except that the named graphs retain their names (as in FROM NAMED).
  87. default-graph-uri - Can be passed any number of times. Works like
  88. context except that plain-URI values should be given, without
  89. wrapping < and > characters.
  90. named-graph-uri - Works like default-graph-uri,
  91. except that this specifies the named graphs to be used.
  92. limit - An integer. Can be used to limit the amount of results
  93. returned by the query.
  94. offset - An integer. Can be used to skip a number of results at
  95. the start of the query.
  96. $[varname] - Parameters starting with a $ character can be used to
  97. bind query variables to fixed value (an N-Triples term)
  98. when executing a SPARQL query.
  99. checkVariables - A boolean that defaults to false, indicating whether
  100. an error should be raised when a SPARQL query selects variables
  101. that are not mentioned in the query body.
  102. defaultGraphName - Can be used to provide a resource (URL) name for
  103. the default graph. Any references to that resource will
  104. reference the default graph, and in the output the resource
  105. will be substituted for any references to the default graph.
  106. Can be given multiple times to have multiple names refer to this
  107. graph, but only the first one will appear in the output.
  108. planner Can be used to control the way the query is planned .
  109. save - When given, will cause the server to (as well as executing
  110. the query normally) save the query as a prepared query under the
  111. name passed as the value for this parameter.
  112. See preparing queries .
  113. '''
  114. super(RepoQuery, self).__init__()
  115. self.query = query
  116. self.query_lng = query_lng
  117. self._response_type = response_type or 'json'
  118. self._content_type = content_type or 'json'
  119. self.infer = str(infer).lower()
  120. self.context = context
  121. self.named_context = named_context
  122. self.default_graph_uri = default_graph_uri
  123. self.named_graph_uri = named_graph_uri
  124. self.limit = limit
  125. self.offset = offset
  126. self.variables = variables
  127. self.check_variables = str(check_variables).lower()
  128. self.default_graph_name = default_graph_name
  129. self.planner = planner
  130. self.save = save #str(save).lower()
  131. self._field_map = {
  132. "query_lng": "queryLn",
  133. "named_context": "namedContext",
  134. "default_graph_uri": "default-graph-uri",
  135. "named_graph_uri": "named-graph-uri",
  136. "check_variables": "checkVariables",
  137. "default_graph_name": "default-graph-name"
  138. }
  139. class SparqlQuery(RepoQuery):
  140. '''wrapper function around RepoQuery to simplfy managing SparqlQueries'''
  141. def __init__(self, query, response_type = None, **kwargs):
  142. self.query_lng = "sparql"
  143. self._response_type = response_type or "sparql+json"
  144. super(SparqlQuery, self).__init__(
  145. query = query,
  146. query_lng = self.query_lng,
  147. response_type = self._response_type,
  148. **kwargs)
  149. class PrologQuery(RepoQuery):
  150. ''' '''
  151. def __init__(self, query, response_type = None, **kwargs):
  152. self.query_lng = 'prolog'
  153. self._response_type = response_type or 'json'
  154. super(PrologQuery, self).__init__(
  155. query = query,
  156. query_lng = self.query_lng,
  157. response_type = self._response_type,
  158. **kwargs)
  159. class StatementQuery(Query):
  160. ''' '''
  161. __cmd__ = "statements"
  162. def __init__(self, format = "ntriples",
  163. subj = None, subj_end = None,
  164. pred = None, pred_end = None,
  165. obj = None, obj_end = None,
  166. context = None,
  167. limit = None,
  168. offset = None,
  169. infer = False
  170. ):
  171. '''
  172. format - look mimetypes.mimetypes keys
  173. subj (GET, DELETE)- Match a specific subject. When given,
  174. should be a term in N-triples format. Can be given multiple times
  175. to mean 'the subject must be one of these resources'.
  176. subjEnd (GET) - can only be given if exactly one subj parameter is given.
  177. Matches a range of subjects.
  178. pred (GET, DELETE)- Match a specific predicate.
  179. Can be passed multiple times, like subj, to match a set.
  180. predEnd (GET)- Perform a range query on the predicate.
  181. obj (GET, DELETE)- Match a specific object. Pass multiple values to
  182. match a set.
  183. objEnd (GET)- Range query on objects.
  184. context (GET/PUT/POST/DELETE)- Used to set the named graph into which
  185. the new data is stored. Can be given multiple times.
  186. Restricts the query to the given list of named graphs.
  187. When not specified, all graphs in the store are used.
  188. contextEnd - Range query on contexts / graph names.
  189. baseURI (PUT/POST)- When loading RDF/XML data, the value of
  190. this parameter is used as the base URI of the document.
  191. commit - (PUT/POST) A positive integer. Will cause a commit to happen after
  192. every N added statements. Can be used to work around the fact that
  193. importing a huge amount of statements in a single transaction will
  194. require excessive amounts of memory.
  195. continueOnError -(PUT/POST) A boolean (default is false) that indicates
  196. whether the load should continue when malformed data is encountered.
  197. Currently only works for N-Triples and N-Quads data.
  198. limit (GET)- An integer indicating the maximum amount of results to return.
  199. offset (GET)- An integer. Tell the server to skip a number of results
  200. before it starts returning.
  201. infer (GET)- Used to turn on reasoning for this query.
  202. Valid values are false, rdfs++, and hasvalue.
  203. Default is false - no reasoning.
  204. format - default ntriple, Possible format - look into mimetypes.
  205. '''
  206. self._response_type = 'text'
  207. self._content_type = 'json'
  208. self.subj = subj
  209. self.subj_end = subj_end
  210. self.pred = pred
  211. self.pred_end = pred_end
  212. self.obj = obj
  213. self.obj_end = obj_end
  214. self.context = context
  215. self.limit = limit
  216. self.offset = offset
  217. self.infer = str(infer).lower()
  218. super(StatementQuery, self).__init__()
  219. def to_format(self):
  220. '''exports query to specified format'''
  221. pass
  222. class GeoQuery(Query):
  223. pass