# -*- coding: utf-8 -*- # """ This is an RDFLib store around Ivan Herman et al.'s SPARQL service wrapper. This was first done in layer-cake, and then ported to RDFLib """ # Defines some SPARQL keywords LIMIT = 'LIMIT' OFFSET = 'OFFSET' ORDERBY = 'ORDER BY' import re import collections import warnings import contextlib try: from SPARQLWrapper import SPARQLWrapper, XML, POST, GET, URLENCODED, POSTDIRECTLY except ImportError: raise Exception( "SPARQLWrapper not found! SPARQL Store will not work." + "Install with 'easy_install SPARQLWrapper'") from rdflib.compat import etree, etree_register_namespace from rdflib.plugins.stores.regexmatching import NATIVE_REGEX from rdflib.store import Store from rdflib.query import Result from rdflib import Variable, Namespace, BNode, URIRef, Literal from rdflib.graph import DATASET_DEFAULT_GRAPH_ID from rdflib.term import Node class NSSPARQLWrapper(SPARQLWrapper): nsBindings = {} def setNamespaceBindings(self, bindings): """ A shortcut for setting namespace bindings that will be added to the prolog of the query @param bindings: A dictionary of prefixs to URIs """ self.nsBindings.update(bindings) def setQuery(self, query): """ Set the SPARQL query text. Note: no check is done on the validity of the query (syntax or otherwise) by this module, except for testing the query type (SELECT, ASK, etc). Syntax and validity checking is done by the SPARQL service itself. @param query: query text @type query: string @bug: #2320024 """ self.queryType = self._parseQueryType(query) self.queryString = self.injectPrefixes(query) def injectPrefixes(self, query): prefixes = list(self.nsBindings.items()) if not prefixes: return query return '\n'.join([ '\n'.join(['PREFIX %s: <%s>' % (k, v) for k, v in prefixes]), '', # separate prefixes from query with an empty line query ]) BNODE_IDENT_PATTERN = re.compile('(?P