SPARQLWrapper.Wrapper module¶
-
SPARQLWrapper.Wrapper.
XML
= 'xml'¶ to be used to set the return format to
XML
(SPARQL Query Results XML
format orRDF/XML
, depending on the query type). This is the default.
-
SPARQLWrapper.Wrapper.
JSON
= 'json'¶ to be used to set the return format to
JSON
.
-
SPARQLWrapper.Wrapper.
JSONLD
= 'json-ld'¶ to be used to set the return format to
JSON-LD
.
-
SPARQLWrapper.Wrapper.
TURTLE
= 'turtle'¶ to be used to set the return format to
Turtle
.
-
SPARQLWrapper.Wrapper.
N3
= 'n3'¶ to be used to set the return format to
N3
(for most of the SPARQL services this is equivalent to Turtle).
-
SPARQLWrapper.Wrapper.
RDF
= 'rdf'¶ to be used to set the return
RDF Graph
.
-
SPARQLWrapper.Wrapper.
RDFXML
= 'rdf+xml'¶ to be used to set the return format to
RDF/XML
explicitly.
-
SPARQLWrapper.Wrapper.
CSV
= 'csv'¶ to be used to set the return format to
CSV
-
SPARQLWrapper.Wrapper.
TSV
= 'tsv'¶ to be used to set the return format to
TSV
-
SPARQLWrapper.Wrapper.
GET
= 'GET'¶ to be used to set HTTP method
GET
. This is the default.
-
SPARQLWrapper.Wrapper.
POST
= 'POST'¶ to be used to set HTTP method
POST
.
-
SPARQLWrapper.Wrapper.
BASIC
= 'BASIC'¶ to be used to set
BASIC
HTTP Authentication method.
-
SPARQLWrapper.Wrapper.
DIGEST
= 'DIGEST'¶ to be used to set
DIGEST
HTTP Authentication method.
-
SPARQLWrapper.Wrapper.
SELECT
= 'SELECT'¶ to be used to set the query type to
SELECT
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
CONSTRUCT
= 'CONSTRUCT'¶ to be used to set the query type to
CONSTRUCT
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
ASK
= 'ASK'¶ to be used to set the query type to
ASK
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
DESCRIBE
= 'DESCRIBE'¶ to be used to set the query type to
DESCRIBE
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
INSERT
= 'INSERT'¶ to be used to set the query type to
INSERT
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
DELETE
= 'DELETE'¶ to be used to set the query type to
DELETE
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
CREATE
= 'CREATE'¶ to be used to set the query type to
CREATE
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
CLEAR
= 'CLEAR'¶ to be used to set the query type to
CLEAR
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
DROP
= 'DROP'¶ to be used to set the query type to
DROP
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
LOAD
= 'LOAD'¶ to be used to set the query type to
LOAD
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
COPY
= 'COPY'¶ to be used to set the query type to
COPY
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
MOVE
= 'MOVE'¶ to be used to set the query type to
MOVE
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
ADD
= 'ADD'¶ to be used to set the query type to
ADD
. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
URLENCODED
= 'urlencoded'¶ to be used to set URL encode as the encoding method for the request. This is, usually, determined automatically.
-
SPARQLWrapper.Wrapper.
POSTDIRECTLY
= 'postdirectly'¶ to be used to set POST directly as the encoding method for the request. This is, usually, determined automatically.
-
class
SPARQLWrapper.Wrapper.
SPARQLWrapper
(endpoint, updateEndpoint=None, returnFormat='xml', defaultGraph=None, agent='sparqlwrapper 1.8.5 (rdflib.github.io/sparqlwrapper)')[source]¶ 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.Variables: - endpoint (string) – SPARQL endpoint’s URI.
- updateEndpoint (string) – SPARQL endpoint’s URI for SPARQL Update operations (if it’s a different one). The default value is
None
. - agent (string) – The User-Agent for the HTTP request header. The default value is an autogenerated string using the SPARQLWrapper version code.
- _defaultGraph (string) – URI for the default graph. The value can be set either via an explicit call
addParameter("default-graph-uri", uri)
or as part of the query string. The default value isNone
. - user (string) – The username of the credentials for querying the current endpoint. The value can be set an explicit call
setCredentials()
. The default value isNone
. - passwd (string) – The password of the credentials for querying the current endpoint. The value can be set an explicit call
setCredentials()
. The default value isNone
. - http_auth (string) – HTTP Authentication type. The default value is
BASIC
. Possible values areBASIC
orDIGEST
. It is used only in case the credentials are set. - onlyConneg (boolean) – Option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters). The default value is
False
. - customHttpHeaders (dict) – Custom HTTP Headers to be included in the request. It is a dictionary where keys are the header field and values are the header values. Important: These headers override previous values (including
Content-Type
,User-Agent
,Accept
andAuthorization
if they are present). - timeout (int) – The timeout (in seconds) to use for querying the endpoint.
- queryString (string) – The SPARQL query text.
- queryType (string) – The type of SPARQL query (aka SPARQL query form), like
CONSTRUCT
,SELECT
,ASK
,DESCRIBE
,INSERT
,DELETE
,CREATE
,CLEAR
,DROP
,LOAD
,COPY
,MOVE
orADD
(constants in this module). - returnFormat (string) – The return format. No local check is done, so 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. The possible values areJSON
,XML
,TURTLE
,N3
,RDF
,RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). The default value isXML
. - requestMethod (string) – The request method for query or update operations. The possibles values are URL-encoded (
URLENCODED
) or POST directly (POSTDIRECTLY
). - method (string) – The invocation method (HTTP verb). The default value is
GET
, but it can be set toPOST
. - parameters (dict) – The parameters of the request (key/value pairs in a dictionary).
- _defaultReturnFormat (string) – The default return format. It is used in case the same class instance is reused for subsequent queries.
- prefix_pattern (
re.RegexObject
, a compiled regular expression. See there
module of Python) – regular expression used to remove base/prefixes in the process of determining the query type. - pattern (
re.RegexObject
, a compiled regular expression. See there
module of Python) – regular expression used to determine whether a query (without base/prefixes) is of typeCONSTRUCT
,SELECT
,ASK
,DESCRIBE
,INSERT
,DELETE
,CREATE
,CLEAR
,DROP
,LOAD
,COPY
,MOVE
orADD
. - comments_pattern (
re.RegexObject
, a compiled regular expression. See there
module of Python) – regular expression used to remove comments from a query.
-
__init__
(endpoint, updateEndpoint=None, returnFormat='xml', defaultGraph=None, agent='sparqlwrapper 1.8.5 (rdflib.github.io/sparqlwrapper)')[source]¶ Class encapsulating a full SPARQL call.
Parameters: - endpoint (string) – SPARQL endpoint’s URI.
- updateEndpoint (string) – SPARQL endpoint’s URI for update operations (if it’s a different one). The default value is
None
. - returnFormat – The return format. No local check is done, so 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. The possible values areJSON
,XML
,TURTLE
,N3
,RDF
,RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). The default value isXML
. - defaultGraph (string) – URI for the default graph. The value can be set either via an explicit call
addParameter("default-graph-uri", uri)
or as part of the query string. The default value isNone
. - agent (string) – The User-Agent for the HTTP request header. The default value is an autogenerated string using the SPARQLWrapper version number.
-
resetQuery
()[source]¶ Reset the query, ie, return format, method, query, default or named graph settings, etc, are reset to their default values. This includes the default values for parameters, method, timeout or requestMethod.
-
setReturnFormat
(format)[source]¶ Set the return format. If the one set is not an allowed value, the setting is ignored.
Parameters: format (string) – Possible values are JSON
,XML
,TURTLE
,N3
,RDF
,RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). All other cases are ignored.Raises: ValueError – If JSONLD
is tried to set and the current instance does not supportJSON-LD
.
-
supportsReturnFormat
(format)[source]¶ Check if a return format is supported.
Parameters: format (string) – Possible values are JSON
,XML
,TURTLE
,N3
,RDF
,RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). All other cases are ignored.Returns: Returns True
if the return format is supported, otherwiseFalse
.Return type: bool
-
setTimeout
(timeout)[source]¶ Set the timeout (in seconds) to use for querying the endpoint.
Parameters: timeout (int) – Timeout in seconds.
-
setOnlyConneg
(onlyConneg)[source]¶ Set this option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters).
New in version 1.8.1.
Parameters: onlyConneg (bool) – True
if only HTTP Content Negotiation is allowed;False
if HTTP parameters are used.
-
setRequestMethod
(method)[source]¶ Set the internal method to use to perform the request for query or update operations, either URL-encoded (
URLENCODED
) or POST directly (POSTDIRECTLY
). Further details at query operation in SPARQL and update operation in SPARQL Update.Parameters: method (string) – Possible values are URLENCODED
(URL-encoded) orPOSTDIRECTLY
(POST directly). All other cases are ignored.
-
addDefaultGraph
(uri)[source]¶ Add a default graph URI.
Deprecated since version 1.6.0: Use
addParameter("default-graph-uri", uri)
instead of this method.Parameters: uri (string) – URI of the default graph.
-
addNamedGraph
(uri)[source]¶ Add a named graph URI.
Deprecated since version 1.6.0: Use
addParameter("named-graph-uri", uri)
instead of this method.Parameters: uri (string) – URI of the named graph.
-
addExtraURITag
(key, value)[source]¶ 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 ofaddParameter()
method.Deprecated since version 1.6.0: Use
addParameter(key, value)
instead of this methodParameters: - key (string) – key of the query part.
- value (string) – value of the query part.
-
addCustomParameter
(name, value)[source]¶ Method is kept for backwards compatibility. Historically, it “replaces” parameters instead of adding.
Deprecated since version 1.6.0: Use
addParameter(key, value)
instead of this methodParameters: - name (string) – name.
- value (string) – value.
Returns: Returns
True
if the adding has been accomplished, otherwiseFalse
.Return type:
-
addParameter
(name, value)[source]¶ 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 parameterquery
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: Returns
True
if the adding has been accomplished, otherwiseFalse
.Return type:
-
addCustomHttpHeader
(httpHeaderName, httpHeaderValue)[source]¶ Add a custom HTTP header (this method can override all HTTP headers).
Important: Take into account that each previous value for the header field names
Content-Type
,User-Agent
,Accept
andAuthorization
would be overriden if the header field name is present as value of the parameterhttpHeaderName
.New in version 1.8.2.
Parameters: - httpHeaderName (string) – The header field name.
- httpHeaderValue (string) – The header field value.
-
clearCustomHttpHeader
(httpHeaderName)[source]¶ Clear the values of a custom HTTP Header previously set. Returns a boolean indicating if the clearing has been accomplished.
New in version 1.8.2.
Parameters: httpHeaderName (string) – HTTP header name. Returns: Returns True
if the clearing has been accomplished, otherwiseFalse
.Return type: bool
-
clearParameter
(name)[source]¶ Clear the values of a concrete parameter. Returns a boolean indicating if the clearing has been accomplished.
Parameters: name (string) – name Returns: Returns True
if the clearing has been accomplished, otherwiseFalse
.Return type: bool
-
setCredentials
(user, passwd, realm='SPARQL')[source]¶ Set the credentials for querying the current endpoint.
Parameters: - user (string) – username.
- passwd (string) – password.
- realm (string) – realm. Only used for
DIGEST
authentication. The default value isSPARQL
Changed in version 1.8.3: Added
realm
parameter.
-
setHTTPAuth
(auth)[source]¶ Set the HTTP Authentication type. Possible values are
BASIC
orDIGEST
.Parameters: auth (string) – auth type.
Raises:
-
setQuery
(query)[source]¶ 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
(query)[source]¶ Internal method for parsing the SPARQL query and return its type (ie,
SELECT
,ASK
, etc).Note
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. The SPARQL endpoint should raise an exception (viaurllib
) for such syntax error.Parameters: query (string) – query text. Returns: the type of SPARQL query (aka SPARQL query form). Return type: string
-
setMethod
(method)[source]¶ Set the invocation method. By default, this is
GET
, but can be set toPOST
.Parameters: method (string) – should be either GET
orPOST
. Other cases are ignored.
-
setUseKeepAlive
()[source]¶ Make
urllib2
use keep-alive.Raises: ImportError – when could not be imported keepalive.HTTPHandler
.
-
isSparqlUpdateRequest
()[source]¶ Returns
True
if SPARQLWrapper is configured for executing SPARQL Update request.Returns: Returns True
if SPARQLWrapper is configured for executing SPARQL Update request.Return type: bool
-
isSparqlQueryRequest
()[source]¶ Returns
True
if SPARQLWrapper is configured for executing SPARQL Query request.Returns: Returns True
if SPARQLWrapper is configured for executing SPARQL Query request.Return type: bool
-
_cleanComments
(query)[source]¶ Internal method for returning the query after all occurrence of singleline comments are removed (issues #32 and #77).
Parameters: query (string) – The query. Returns: the query after all occurrence of singleline comments are removed. Return type: string
-
_getRequestEncodedParameters
(query=None)[source]¶ Internal method for getting the request encoded parameters.
Parameters: query (tuple) – a tuple of two items. The first item can be the string query
(forSELECT
,DESCRIBE
,ASK
,CONSTRUCT
query) or the stringupdate
(for SPARQL Update queries, likeDELETE
orINSERT
). The second item of the tuple is the query string itself.Returns: the request encoded parameters. Return type: string
-
_createRequest
()[source]¶ Internal method to create request according a HTTP method. Returns a
urllib2.Request
object of theurllib2
Python libraryRaises: NotImplementedError – If the HTTP authentification method is not one of the valid values: BASIC
orDIGEST
.Returns: request a urllib2.Request
object of theurllib2
Python library
-
_query
()[source]¶ Internal method to execute the query. Returns the output of the
urllib2.urlopen()
method of theurllib2
Python libraryReturns: tuples with the raw request plus the expected format.
Raises: - QueryBadFormed – If the HTTP return code is
400
. - Unauthorized – If the HTTP return code is
401
. - EndPointNotFound – If the HTTP return code is
404
. - URITooLong – If the HTTP return code is
414
. - EndPointInternalError – If the HTTP return code is
500
. - urllib2.HTTPError – If the HTTP return code is different to
400
,401
,404
,414
,500
.
- QueryBadFormed – If the HTTP return code is
-
query
()[source]¶ 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: query result Return type: QueryResult
instance
-
class
SPARQLWrapper.Wrapper.
QueryResult
(result)[source]¶ Wrapper around an a query result. Users should not create instances of this class, it is generated by a
SPARQLWrapper.query()
call. The results can be converted to various formats, or used directly.If used directly: the class gives access to the direct HTTP request results
response
obtained from the call tourllib.urlopen()
. It is a file-like object with two additional methods:geturl()
to return the URL of the resource retrievedinfo()
that returns the meta-information of the HTTP result as a dictionary-like object.
For convenience, these methods are also available on the
QueryResult
instance.The
__iter__()
andnext()
methods are also implemented (by mapping them toresponse
). This means that the common idiomfor l in obj : do_something_with_line(l)
would work, too.Variables: -
__init__
(result)[source]¶ Parameters: result – HTTP response stemming from a SPARQLWrapper.query()
call, or a tuple with the expected format: (response, format).
-
geturl
()[source]¶ Return the URL of the original call.
Returns: URL of the original call. Return type: string
-
info
()[source]¶ Return the meta-information of the HTTP result.
Returns: meta-information of the HTTP result. Return type: dict
-
_convertJSON
()[source]¶ Convert a JSON result into a Python dict. This method can be overwritten in a subclass for a different conversion method.
Returns: converted result. Return type: dict
-
_convertXML
()[source]¶ Convert an XML result into a Python dom tree. This method can be overwritten in a subclass for a different conversion method.
Returns: converted result. Return type: xml.dom.minidom.Document
-
_convertRDF
()[source]¶ Convert a RDF/XML result into an RDFLib Graph. This method can be overwritten in a subclass for a different conversion method.
Returns: converted result. Return type: rdflib.graph.Graph
-
_convertN3
()[source]¶ Convert a RDF Turtle/N3 result into a string. This method can be overwritten in a subclass for a different conversion method.
Returns: converted result. Return type: string
-
_convertCSV
()[source]¶ Convert a CSV result into a string. This method can be overwritten in a subclass for a different conversion method.
Returns: converted result. Return type: string
-
_convertTSV
()[source]¶ Convert a TSV result into a string. This method can be overwritten in a subclass for a different conversion method.
Returns: converted result. Return type: string
-
_convertJSONLD
()[source]¶ Convert a RDF JSON-LD result into an RDFLib Graph. This method can be overwritten in a subclass for a different conversion method.
Returns: converted result Return type: rdflib.graph.Graph
-
convert
()[source]¶ Encode the return value depending on the return format:
- in the case of
XML
, a DOM top element is returned - in the case of
JSON
, a json conversion will return a dictionary - in the case of
RDF/XML
, the value is converted via RDFLib into aRDFLib Graph
instance - in the case of
JSON-LD
, the value is converted via RDFLib into aRDFLib Graph
instance - in the case of RDF
Turtle
/N3
, a string is returned - in the case of
CSV
/TSV
, a string is returned - In all other cases the input simply returned.
Returns: the converted query result. See the conversion methods for more details. - in the case of
-
_get_responseFormat
()[source]¶ Get the response (return) format. The possible values are:
JSON
,XML
,RDFXML
,TURTLE
,N3
,CSV
,TSV
,JSONLD
. In case there is no Content-Type,None
is return. In all other cases, the raw Content-Type is return.New in version 1.8.3.
Returns: the response format. The possible values are: JSON
,XML
,RDFXML
,TURTLE
,N3
,CSV
,TSV
,JSONLD
.Return type: string
-
print_results
(minWidth=None)[source]¶ This method prints a representation of a
QueryResult
object that MUST has as response formatJSON
.Parameters: minWidth (string) – The minimum width, counting as characters. The default value is None
.