graph_store_connector.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import logging
  2. import uuid
  3. from flask import request
  4. from rdflib import Dataset
  5. from rdflib.plugins.stores.sparqlstore import SPARQLUpdateStore
  6. from rdflib.term import URIRef
  7. from lakesuperior.config_parser import config
  8. from lakesuperior.core.namespaces import ns_collection as nsc
  9. from lakesuperior.core.namespaces import ns_mgr as nsm
  10. class GraphStoreConnector:
  11. '''Connector for LDP-RS (RDF Source) resources. Connects to a
  12. triplestore.
  13. '''
  14. _conf = config['application']['store']['ldp_rs']
  15. _logger = logging.getLogger(__module__)
  16. query_ep = _conf['webroot'] + _conf['query_ep']
  17. update_ep = _conf['webroot'] + _conf['update_ep']
  18. ## MAGIC METHODS ##
  19. @property
  20. def store(self):
  21. if not hasattr(self, '_store') or not self._store:
  22. self._store = SPARQLUpdateStore(
  23. queryEndpoint=self.query_ep,
  24. update_endpoint=self.update_ep,
  25. autocommit=False,
  26. dirty_reads=True)
  27. return self._store
  28. def __init__(self):
  29. '''Initialize the graph store.
  30. NOTE: `rdflib.Dataset` requires a RDF 1.1 compliant store with support
  31. for Graph Store HTTP protocol
  32. (https://www.w3.org/TR/sparql11-http-rdf-update/). Blazegraph supports
  33. this only in the (currently) unreleased 2.2 branch. It works with Jena,
  34. but other considerations would have to be made (e.g. Jena has no REST
  35. API for handling transactions).
  36. In a more advanced development phase it could be possible to extend the
  37. SPARQLUpdateStore class to add non-standard interaction with specific
  38. SPARQL implementations in order to support ACID features provided
  39. by them; e.g. Blazegraph's RESTful transaction handling methods.
  40. '''
  41. self.ds = Dataset(self.store, default_union=True)
  42. self.ds.namespace_manager = nsm
  43. #def __del__(self):
  44. # '''Commit pending transactions and close connection.'''
  45. # self.store.close(True)
  46. ## PUBLIC METHODS ##
  47. def query(self, q, initBindings=None, nsc=nsc):
  48. '''
  49. Perform a custom query on the triplestore.
  50. @param q (string) SPARQL query.
  51. @return rdflib.query.Result
  52. '''
  53. self._logger.debug('Querying SPARQL endpoint: {}'.format(q))
  54. return self.ds.query(q, initBindings=initBindings, initNs=nsc)