Package SPARQLWrapper :: Module Wrapper :: Class SPARQLWrapper
[hide private]
[frames] | no frames]

Class SPARQLWrapper

source code

object --+
         |
        SPARQLWrapper
Known Subclasses:

Wrapper around an online access to a SPARQL Web entry point.

The same class instance can be reused for subsequent queries. The values of the base Graph URI, return formats, etc, are retained from one query to the next (in other words, only the query string changes). The instance can also be reset to its initial values using the resetQuery method.

Instance Methods [hide private]
 
__init__(self, endpoint, updateEndpoint=None, returnFormat='xml', defaultGraph=None, agent='sparqlwrapper 1.8.2 (rdflib.github.io/sparqlwrapper)')
Class encapsulating a full SPARQL call.
source code
 
resetQuery(self)
Reset the query, ie, return format, method, query, default or named graph settings, etc, are reset to their default values.
source code
 
setReturnFormat(self, format)
Set the return format.
source code
bool
supportsReturnFormat(self, format)
Check if a return format is supported.
source code
 
setTimeout(self, timeout)
Set the timeout (in seconds) to use for querying the endpoint.
source code
 
setOnlyConneg(self, onlyConneg)
Set this option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters).
source code
 
setRequestMethod(self, method)
Set the internal method to use to perform the request for query or update operations, either URL-encoded (SPARQLWrapper.URLENCODED) or POST directly (SPARQLWrapper.POSTDIRECTLY).
source code
 
addDefaultGraph(self, uri)
Add a default graph URI.
source code
 
addNamedGraph(self, uri)
Add a named graph URI.
source code
 
addExtraURITag(self, key, value)
Some SPARQL endpoints require extra key value pairs.
source code
bool
addCustomParameter(self, name, value)
Method is kept for backwards compatibility.
source code
bool
addParameter(self, name, value)
Some SPARQL endpoints allow extra key value pairs.
source code
 
addCustomHttpHeader(self, httpHeaderName, httpHeaderValue)
Add a custom HTTP header (this method can override all HTTP headers).
source code
bool
clearCustomHttpHeader(self, httpHeaderName)
Clear the values of a custom Http Header previously setted.
source code
bool
clearParameter(self, name)
Clear the values of a concrete parameter.
source code
 
setCredentials(self, user, passwd)
Set the credentials for querying the current endpoint.
source code
 
setHTTPAuth(self, auth)
Set the HTTP Authentication type.
source code
 
setQuery(self, query)
Set the SPARQL query text.
source code
string
_parseQueryType(self, query)
Internal method for parsing the SPARQL query and return its type (ie, SELECT, ASK, etc).
source code
 
setMethod(self, method)
Set the invocation method.
source code
 
setUseKeepAlive(self)
Make urllib2 use keep-alive.
source code
bool
isSparqlUpdateRequest(self)
Returns TRUE if SPARQLWrapper is configured for executing SPARQL Update request.
source code
bool
isSparqlQueryRequest(self)
Returns TRUE if SPARQLWrapper is configured for executing SPARQL Query request.
source code
string
_cleanComments(self, query)
Internal method for returning the query after all occurrence of singleline comments are removed (issues #32 and #77).
source code
 
_getRequestEncodedParameters(self, query=None)
Internal method for getting the request encoded parameters.
source code
 
_getAcceptHeader(self)
Internal method for getting the HTTP Accept Header.
source code
 
_createRequest(self)
Internal method to create request according a HTTP method.
source code
 
_query(self)
Internal method to execute the query.
source code
QueryResult instance
query(self)
Execute the query.
source code
 
queryAndConvert(self)
Macro like method: issue a query and return the converted results.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Class Variables [hide private]
compiled regular expression (see the re module of Python) pattern = re.compile(r'(?ix)((?P<base>(\s*BASE\s*<.*?>)\s*)|(?...
regular expression used to determine whether a query is of type CONSTRUCT, SELECT, ASK, or DESCRIBE.
  comments_pattern = re.compile(r'(^|\n)\s*#.*?\n')
Instance Variables [hide private]
string _defaultGraph
URI for the default graph.
string agent
The User-Agent for the HTTP request header.
dict customHttpHeaders
Custom HTTP Headers to be included in the request.
string endpoint
SPARQL endpoint's URI
string http_auth
HTTP Authentication type.
boolean onlyConneg
Option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters).The default value is False.
string passwd
The password of the credentials for querying the current endpoint.
string updateEndpoint
SPARQL endpoint's URI for update operations (if it's a different one).
string user
The username of the credentials for querying the current endpoint.
Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, endpoint, updateEndpoint=None, returnFormat='xml', defaultGraph=None, agent='sparqlwrapper 1.8.2 (rdflib.github.io/sparqlwrapper)')
(Constructor)

source code 

Class encapsulating a full SPARQL call.

Parameters:
  • endpoint (string) - string of the SPARQL endpoint's URI
  • updateEndpoint (string) - string of the SPARQL endpoint's URI for update operations (if it's a different one)
  • returnFormat (string) - Default: XML. Can be set to JSON or Turtle/N3

    No local check is done, the parameter is simply sent to the endpoint. Eg, if the value is set to JSON and a construct query is issued, it is up to the endpoint to react or not, this wrapper does not check.

    Possible values: JSON, XML, TURTLE, N3, RDFXML, CSV, TSV (constants in this module). The value can also be set via explicit call, see below.

  • defaultGraph (string) - URI for the default graph. Default is None, the value can be set either via an explicit call or as part of the query string.
  • agent (string) - The User-Agent for the HTTP request header.
Overrides: object.__init__

setReturnFormat(self, format)

source code 

Set the return format. If not an allowed value, the setting is ignored.

Parameters:
Raises:
  • ValueError - If JSONLD is tried to set and the current instance does not support JSON-LD.

supportsReturnFormat(self, format)

source code 

Check if a return format is supported.

Parameters:
Returns: bool
Returns a boolean after checking if a return format is supported.

setTimeout(self, timeout)

source code 

Set the timeout (in seconds) to use for querying the endpoint.

Parameters:
  • timeout (int) - Timeout in seconds.

setOnlyConneg(self, onlyConneg)

source code 

Set this option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters).

Parameters:
  • onlyConneg (bool) - True if only HTTP Content Negotiation is allowed; False is HTTP parameters are allowed also.

Since: 1.8.1

setRequestMethod(self, method)

source code 

Set the internal method to use to perform the request for query or update operations, either URL-encoded (SPARQLWrapper.URLENCODED) or POST directly (SPARQLWrapper.POSTDIRECTLY). Further details at http://www.w3.org/TR/sparql11-protocol/#query-operation and http://www.w3.org/TR/sparql11-protocol/#update-operation.

Parameters:
  • method (string) - Possible values are SPARQLWrapper.URLENCODED (URL-encoded) or SPARQLWrapper.POSTDIRECTLY (POST directly). All other cases are ignored.

addDefaultGraph(self, uri)

source code 

Add a default graph URI.

Parameters:
  • uri (string) - URI of the graph

Deprecated: use addParameter("default-graph-uri", uri) instead of this method

addNamedGraph(self, uri)

source code 

Add a named graph URI.

Parameters:
  • uri (string) - URI of the graph

Deprecated: use addParameter("named-graph-uri", uri) instead of this method

addExtraURITag(self, key, value)

source code 

Some SPARQL endpoints require extra key value pairs. E.g., in virtuoso, one would add should-sponge=soft to the query forcing virtuoso to retrieve graphs that are not stored in its local database. Alias of SPARQLWrapper.addParameter method.

Parameters:
  • key (string) - key of the query part
  • value (string) - value of the query part

Deprecated: use addParameter(key, value) instead of this method

addCustomParameter(self, name, value)

source code 

Method is kept for backwards compatibility. Historically, it "replaces" parameters instead of adding.

Parameters:
  • name (string) - name
  • value (string) - value
Returns: bool
Returns a boolean indicating if the adding has been accomplished.

Deprecated: use addParameter(name, value) instead of this method

addParameter(self, name, value)

source code 

Some SPARQL endpoints allow extra key value pairs. E.g., in virtuoso, one would add should-sponge=soft to the query forcing virtuoso to retrieve graphs that are not stored in its local database. If the param query is tried to be set, this intent is dismissed. Returns a boolean indicating if the set has been accomplished.

Parameters:
  • name (string) - name
  • value (string) - value
Returns: bool
Returns a boolean indicating if the adding has been accomplished.

addCustomHttpHeader(self, httpHeaderName, httpHeaderValue)

source code 

Add a custom HTTP header (this method can override all HTTP headers). IMPORTANT: Take into acount that each previous value for the header field names Content-Type, User-Agent, Accept and Authorization would be overriden if the header field name is present as value of the parameter httpHeaderName.

Parameters:
  • httpHeaderName (string) - The header field name.
  • httpHeaderValue (string) - The header field value.

Since: 1.8.2

clearCustomHttpHeader(self, httpHeaderName)

source code 

Clear the values of a custom Http Header previously setted. Returns a boolean indicating if the clearing has been accomplished.

Parameters:
  • httpHeaderName (string) - name
Returns: bool
Returns a boolean indicating if the clearing has been accomplished.

Since: 1.8.2

clearParameter(self, name)

source code 

Clear the values of a concrete parameter. Returns a boolean indicating if the clearing has been accomplished.

Parameters:
  • name (string) - name
Returns: bool
Returns a boolean indicating if the clearing has been accomplished.

setCredentials(self, user, passwd)

source code 

Set the credentials for querying the current endpoint.

Parameters:
  • user (string) - username
  • passwd (string) - password

setHTTPAuth(self, auth)

source code 

Set the HTTP Authentication type. Possible values are BASIC or DIGEST.

Parameters:
  • auth (string) - auth type
Raises:
  • TypeError - If the auth parameter is not an string.
  • ValueError - If the auth parameter has not one of the valid values: BASIC or DIGEST.

setQuery(self, query)

source code 

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.

Parameters:
  • query (string) - query text
Raises:
  • TypeError - If the query parameter is not an unicode-string or utf-8 encoded byte-string.

_parseQueryType(self, query)

source code 

Internal method for parsing the SPARQL query and return its type (ie, SELECT, ASK, etc).

Note that the method returns SELECT if nothing is specified. This is just to get all other methods running; in fact, this means that the query is erroneous, because the query must be, according to the SPARQL specification, one of Select, Ask, Describe, or Construct. The SPARQL endpoint should raise an exception (via urllib) for such syntax error.

Parameters:
  • query (string) - query text
Returns: string
the type of SPARQL query (aka SPARQL query form)

setMethod(self, method)

source code 

Set the invocation method. By default, this is GET, but can be set to POST.

Parameters:
  • method (string) - should be either GET or POST. Other cases are ignored.

setUseKeepAlive(self)

source code 

Make urllib2 use keep-alive.

Raises:
  • ImportError - when could not be imported keepalive.HTTPHandler

isSparqlUpdateRequest(self)

source code 

Returns TRUE if SPARQLWrapper is configured for executing SPARQL Update request.

Returns: bool
Returns TRUE if SPARQLWrapper is configured for executing SPARQL Update request

isSparqlQueryRequest(self)

source code 

Returns TRUE if SPARQLWrapper is configured for executing SPARQL Query request.

Returns: bool
Returns TRUE if SPARQLWrapper is configured for executing SPARQL Query request.

_cleanComments(self, query)

source code 

Internal method for returning the query after all occurrence of singleline comments are removed (issues #32 and #77).

Parameters:
  • query (string) - The query
Returns: string
the query after all occurrence of singleline comments are removed.

_getRequestEncodedParameters(self, query=None)

source code 

Internal method for getting the request encoded parameters.

Parameters:
  • query (string) - The query

_getAcceptHeader(self)

source code 

Internal method for getting the HTTP Accept Header.

_createRequest(self)

source code 

Internal method to create request according a HTTP method. Returns a urllib2.Request object of the urllib2 Python library

Returns:
request a urllib2.Request object of the urllib2 Python library
Raises:
  • NotImplementedError - If the HTTP authentification method is not one of the valid values: BASIC or DIGEST.

_query(self)

source code 

Internal method to execute the query. Returns the output of the urllib2.urlopen method of the standard Python library

Returns:
tuples with the raw request plus the expected format.
Raises:

query(self)

source code 

Execute the query. Exceptions can be raised if either the URI is wrong or the HTTP sends back an error (this is also the case when the query is syntactically incorrect, leading to an HTTP error sent back by the SPARQL endpoint). The usual urllib2 exceptions are raised, which therefore cover possible SPARQL errors, too.

Note that some combinations of return formats and query types may not make sense. For example, a SELECT query with Turtle response is meaningless (the output of a SELECT is not a Graph), or a CONSTRUCT query with JSON output may be a problem because, at the moment, there is no accepted JSON serialization of RDF (let alone one implemented by SPARQL endpoints). In such cases the returned media type of the result is unpredictable and may differ from one SPARQL endpoint implementation to the other. (Endpoints usually fall back to one of the "meaningful" formats, but it is up to the specific implementation to choose which one that is.)

Returns: QueryResult instance
query result

queryAndConvert(self)

source code 

Macro like method: issue a query and return the converted results.

Returns:
the converted query result. See the conversion methods for more details.

Class Variable Details [hide private]

pattern

regular expression used to determine whether a query is of type CONSTRUCT, SELECT, ASK, or DESCRIBE.
Type:
compiled regular expression (see the re module of Python)
Value:
re.compile(r'(?ix)((?P<base>(\s*BASE\s*<.*?>)\s*)|(?P<prefixes>(\s*PRE\
FIX\s+.+:\s*<.*?>)\s*))*(?P<queryType>(CONSTRUCT|SELECT|ASK|DESCRIBE|I\
NSERT|DELETE|CREATE|CLEAR|DROP|LOAD|COPY|MOVE|ADD))')

Instance Variable Details [hide private]

_defaultGraph

URI for the default graph. Default is None, the value can be set either via an explicit call("default-graph-uri", uri) or as part of the query string.
Type:
string

customHttpHeaders

Custom HTTP Headers to be included in the request. Important: These headers override previous values (including Content-Type, User-Agent, Accept and Authorization if they are present). It is a dictionary where keys are the header field nada and values are the header values.
Type:
dict

http_auth

HTTP Authentication type. The default value is BASIC. Possible values are BASIC or DIGEST
Type:
string

passwd

The password of the credentials for querying the current endpoint. Default is None, the value can be set an explicit call.
Type:
string

updateEndpoint

SPARQL endpoint's URI for update operations (if it's a different one). Default is None
Type:
string

user

The username of the credentials for querying the current endpoint. Default is None, the value can be set an explicit call.
Type:
string