graph_store_connector.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import logging
  2. from rdflib import Dataset
  3. from rdflib.plugins.sparql import prepareQuery
  4. from rdflib.plugins.stores.sparqlstore import SPARQLUpdateStore
  5. from lakesuperior.config_parser import config
  6. class GraphStoreConnector:
  7. '''Connector for LDP-RS (RDF Source) resources. Connects to a
  8. triplestore.'''
  9. _conf = config['application']['store']['ldp_rs']
  10. _logger = logging.getLogger(__module__)
  11. ## MAGIC METHODS ##
  12. def __init__(self, method=POST):
  13. '''Initialize the graph store.
  14. @param method (string) HTTP method to use for the query. POST is the
  15. default and recommended value since it places virtually no limitation
  16. on the query string length.
  17. NOTE: `rdflib.Dataset` requires a RDF 1.1 compliant store with support
  18. for Graph Store HTTP protocol
  19. (https://www.w3.org/TR/sparql11-http-rdf-update/). This may not be
  20. viable with the current version of Blazegraph. It would with Fuseki,
  21. but other considerations would have to be made (e.g. Jena has no REST
  22. API for handling transactions).
  23. '''
  24. self._store = SPARQLUpdateStore(queryEnpdpoint=self._conf['query_ep'],
  25. update_endpoint=self._conf['update_ep'])
  26. try:
  27. self._store.open(self._conf['base_url'])
  28. except:
  29. raise RuntimeError('Error opening remote graph store.')
  30. self.dataset = Dataset(self._store)
  31. def __del__(self):
  32. '''Commit pending transactions and close connection.'''
  33. self._store.close(True)
  34. ## PUBLIC METHODS ##
  35. def query(self, q, initNs=None, initBindings=None):
  36. '''Query the triplestore.
  37. @param q (string) SPARQL query.
  38. @return rdflib.query.Result
  39. '''
  40. self._logger.debug('Querying SPARQL endpoint: {}'.format(q))
  41. return self.dataset.query(q, initNs=initNs or nsc,
  42. initBindings=initBindings)
  43. def find_by_type(self, type):
  44. '''Find all resources by RDF type.
  45. @param type (rdflib.term.URIRef) RDF type to query.
  46. '''
  47. return self.query('SELECT ?s {{?s a {} . }}'.format(type.n3()))