query.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import logging
  2. from flask import Blueprint, current_app, request, render_template
  3. from rdflib.plugin import PluginException
  4. from lakesuperior.env import env
  5. from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
  6. from lakesuperior.api import query as query_api
  7. from lakesuperior.store.ldp_rs.lmdb_store import LmdbStore, TxnManager
  8. # Query endpoint. raw SPARQL queries exposing the underlying layout can be made
  9. # available. Also convenience methods that allow simple lookups based on simple
  10. # binary comparisons should be added. Binary lookups—maybe?
  11. # N.B All data sources are read-only for this endpoint.
  12. logger = logging.getLogger(__name__)
  13. rdf_store = env.app_globals.rdf_store
  14. rdfly = env.app_globals.rdfly
  15. query = Blueprint('query', __name__)
  16. @query.route('/term_search', methods=['GET'])
  17. def term_search():
  18. '''
  19. Search by entering a search term and optional property and comparison term.
  20. '''
  21. valid_operands = (
  22. ('=', 'Equals'),
  23. ('>', 'Greater Than'),
  24. ('<', 'Less Than'),
  25. ('<>', 'Not Equal'),
  26. ('a', 'RDF Type'),
  27. )
  28. term = request.args.get('term')
  29. prop = request.args.get('prop', default=1)
  30. cmp = request.args.get('cmp', default='=')
  31. return render_template('term_search.html')
  32. @query.route('/sparql', methods=['GET', 'POST'])
  33. def sparql():
  34. '''
  35. Perform a direct SPARQL query on the underlying triplestore.
  36. @param qry SPARQL query string.
  37. '''
  38. accept_mimetypes = {
  39. 'text/csv': 'csv',
  40. 'application/sparql-results+json': 'json',
  41. 'application/sparql-results+xml': 'xml',
  42. }
  43. if request.method == 'GET':
  44. return render_template('sparql_query.html', nsm=nsm)
  45. else:
  46. if request.mimetype == 'multipart/form-data':
  47. qstr = request.form['query']
  48. else:
  49. qstr = stream.read()
  50. logger.debug('Query: {}'.format(qstr))
  51. with TxnManager(rdf_store) as txn:
  52. qres = query_api.sparql_query(qstr)
  53. match = request.accept_mimetypes.best_match(accept_mimetypes.keys())
  54. if match:
  55. enc = accept_mimetypes[match]
  56. else:
  57. enc = request.accept_mimetypes.best
  58. try:
  59. out = qres.serialize(format=enc)
  60. except PluginException:
  61. return (
  62. 'Unable to serialize results into format {}'.format(enc),
  63. 406)
  64. return out, 200