Skip to content

Commit

Permalink
fixed some identantion issue based on contribution from RDFLib#143
Browse files Browse the repository at this point in the history
  • Loading branch information
dayures authored and t0b3 committed May 5, 2020
1 parent 33a497e commit 00b0bf5
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 46 deletions.
1 change: 1 addition & 0 deletions SPARQLWrapper/KeyCaseInsensitiveDict.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
:license: `W3C® Software notice and license <http://www.w3.org/Consortium/Legal/copyright-software>`_
"""


class KeyCaseInsensitiveDict(dict):
"""
A simple implementation of a key case-insensitive dictionary
Expand Down
3 changes: 3 additions & 0 deletions SPARQLWrapper/SPARQLExceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def __init__(self, response=None):

super(SPARQLWrapperException, self).__init__(formatted_msg)


class EndPointInternalError(SPARQLWrapperException):
"""
Exception type for Internal Server Error responses. Usually HTTP response status code ``500``.
Expand All @@ -63,6 +64,7 @@ class EndPointNotFound(SPARQLWrapperException):

msg = "it was impossible to connect with the endpoint in that address, check if it is correct"


class Unauthorized(SPARQLWrapperException):
"""
Access is denied due to invalid credentials (unauthorized). Usually HTTP response status code ``401``.
Expand All @@ -72,6 +74,7 @@ class Unauthorized(SPARQLWrapperException):

msg = "access is denied due to invalid credentials (unauthorized). Check the credentials"


class URITooLong(SPARQLWrapperException):
"""
The URI requested by the client is longer than the server is willing to interpret. Usually HTTP response status code ``414``.
Expand Down
7 changes: 4 additions & 3 deletions SPARQLWrapper/SmartWrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

######################################################################################


class Value(object):
"""
Class encapsulating a single binding for a variable.
Expand Down Expand Up @@ -120,8 +121,8 @@ def __init__(self, retval):
self.bindings = []
try:
for b in self.fullResult['results']['bindings']:
# this is a single binding. It is a dictionary per variable; each value is a dictionary again that has to be
# converted into a Value instance
# This is a single binding. It is a dictionary per variable; each value is a dictionary again
# that has to be converted into a Value instance
newBind = {}
for key in self.variables:
if key in b:
Expand Down Expand Up @@ -246,7 +247,7 @@ def _nonSliceCase(key):
continue
if True in [k in b for k in no_keys]:
continue
# if we got that far, we shouild be all right!
# if we got that far, we should be all right!
retval.append(b)
# if retval is of zero length, no hit; an exception should be raised to stay within the python style
if len(retval) == 0:
Expand Down
46 changes: 24 additions & 22 deletions SPARQLWrapper/Wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@
_allowedFormats.append(JSONLD)
_RDF_POSSIBLE = _RDF_POSSIBLE + _RDF_JSONLD
except ImportError:
#warnings.warn("JSON-LD disabled because no suitable support has been found", RuntimeWarning)
# warnings.warn("JSON-LD disabled because no suitable support has been found", RuntimeWarning)
pass

# This is very ugly. The fact is that the key for the choice of the output format is not defined.
Expand Down Expand Up @@ -233,7 +233,7 @@ def __init__(self, endpoint, updateEndpoint=None, returnFormat=XML, defaultGraph
self.passwd = None
self.http_auth = BASIC
self._defaultGraph = defaultGraph
self.onlyConneg = False # Only Content Negotiation
self.onlyConneg = False # Only Content Negotiation
self.customHttpHeaders = {}

if returnFormat in _allowedFormats:
Expand Down Expand Up @@ -538,7 +538,7 @@ def _parseQueryType(self, query):
if r_queryType in _allowedQueryTypes:
return r_queryType
else:
#raise Exception("Illegal SPARQL Query; must be one of SELECT, ASK, DESCRIBE, or CONSTRUCT")
# raise Exception("Illegal SPARQL Query; must be one of SELECT, ASK, DESCRIBE, or CONSTRUCT")
warnings.warn("unknown query type '%s'" % r_queryType, RuntimeWarning)
return SELECT

Expand Down Expand Up @@ -624,9 +624,9 @@ def _getRequestEncodedParameters(self, query=None):
# "tsv", "rdf+xml" and "json-ld" are not supported as a correct "output"/"format" parameter value but "text/tab-separated-values" or "application/rdf+xml" are a valid values,
# and there is no problem to send both (4store does not support unexpected values).
if self.returnFormat in [TSV, JSONLD, RDFXML]:
acceptHeader = self._getAcceptHeader() # to obtain the mime-type "text/tab-separated-values" or "application/rdf+xml"
acceptHeader = self._getAcceptHeader() # to obtain the mime-type "text/tab-separated-values" or "application/rdf+xml"
if "*/*" in acceptHeader:
acceptHeader = "" # clear the value in case of "*/*"
acceptHeader = "" # clear the value in case of "*/*"
query_parameters[f] += [acceptHeader]

pairs = (
Expand All @@ -648,9 +648,9 @@ def _getAcceptHeader(self):
acceptHeader = ",".join(_SPARQL_XML)
elif self.returnFormat == JSON:
acceptHeader = ",".join(_SPARQL_JSON)
elif self.returnFormat == CSV: # Allowed for SELECT and ASK (https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-success) but only described for SELECT (https://www.w3.org/TR/sparql11-results-csv-tsv/)
elif self.returnFormat == CSV: # Allowed for SELECT and ASK (https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-success) but only described for SELECT (https://www.w3.org/TR/sparql11-results-csv-tsv/)
acceptHeader = ",".join(_CSV)
elif self.returnFormat == TSV: # Allowed for SELECT and ASK (https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-success) but only described for SELECT (https://www.w3.org/TR/sparql11-results-csv-tsv/)
elif self.returnFormat == TSV: # Allowed for SELECT and ASK (https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-success) but only described for SELECT (https://www.w3.org/TR/sparql11-results-csv-tsv/)
acceptHeader = ",".join(_TSV)
else:
acceptHeader = ",".join(_ALL)
Expand Down Expand Up @@ -688,7 +688,7 @@ def _createRequest(self):
request = None

if self.isSparqlUpdateRequest():
#protocol details at http://www.w3.org/TR/sparql11-protocol/#update-operation
# protocol details at http://www.w3.org/TR/sparql11-protocol/#update-operation
uri = self.updateEndpoint

if self.method != POST:
Expand All @@ -703,7 +703,7 @@ def _createRequest(self):
request.add_header("Content-Type", "application/x-www-form-urlencoded")
request.data = self._getRequestEncodedParameters(("update", self.queryString)).encode('ascii')
else:
#protocol details at http://www.w3.org/TR/sparql11-protocol/#query-operation
# protocol details at http://www.w3.org/TR/sparql11-protocol/#query-operation
uri = self.endpoint

if self.method == POST:
Expand Down Expand Up @@ -844,6 +844,7 @@ class QueryResult(object):
:type requestedFormat: string
"""

def __init__(self, result):
"""
:param result: HTTP response stemming from a :func:`SPARQLWrapper.query` call, or a tuple with the expected format: (response, format).
Expand Down Expand Up @@ -916,7 +917,7 @@ def _convertRDF(self):
retval = ConjunctiveGraph()
# (DEPRECATED) this is a strange hack. If the publicID is not set, rdflib (or the underlying xml parser) makes a funny
# (DEPRECATED) (and, as far as I could see, meaningless) error message...
retval.load(self.response) # (DEPRECATED) publicID=' ')
retval.load(self.response) # (DEPRECATED) publicID=' ')
return retval

def _convertN3(self):
Expand Down Expand Up @@ -959,7 +960,7 @@ def _convertJSONLD(self):
"""
from rdflib import ConjunctiveGraph
retval = ConjunctiveGraph()
retval.load(self.response, format='json-ld')# (DEPRECATED), publicID=' ')
retval.load(self.response, format='json-ld') # (DEPRECATED), publicID=' ')
return retval

def convert(self):
Expand All @@ -976,6 +977,7 @@ def convert(self):
:return: the converted query result. See the conversion methods for more details.
"""

def _content_type_in_list(real, expected):
""" Internal method for checking if the content-type header received matches any of the content types of the expected list.
Expand Down Expand Up @@ -1006,7 +1008,7 @@ def _validate_format(format_name, allowed, mime, requested):

# TODO. In order to compare properly, the requested QueryType (SPARQL Query Form) is needed. For instance, the unexpected N3 requested for a SELECT would return XML
if "content-type" in self.info():
ct = self.info()["content-type"] # returned Content-Type value
ct = self.info()["content-type"] # returned Content-Type value

if _content_type_in_list(ct, _SPARQL_XML):
_validate_format("XML", [XML], ct, self.requestedFormat)
Expand Down Expand Up @@ -1060,7 +1062,7 @@ def _content_type_in_list(real, expected):
return True in [real.find(mime) != -1 for mime in expected]

if "content-type" in self.info():
ct = self.info()["content-type"] # returned Content-Type value
ct = self.info()["content-type"] # returned Content-Type value

if _content_type_in_list(ct, _SPARQL_XML):
return XML
Expand Down Expand Up @@ -1106,22 +1108,22 @@ def print_results(self, minWidth=None):
width = self.__get_results_width(results)
index = 0
for var in results["head"]["vars"]:
print ("?" + var).ljust(width[index]), "|",
print(("?" + var).ljust(width[index]), "|",)
index += 1
print
print "=" * (sum(width) + 3 * len(width))
print()
print("=" * (sum(width) + 3 * len(width)))
for result in results["results"]["bindings"]:
index = 0
for var in results["head"]["vars"]:
result_value = self.__get_prettyprint_string_sparql_var_result(result[var])
print result_value.ljust(width[index]), "|",
print(result_value.ljust(width[index]), "|",)
index += 1
print
print()

def __get_results_width(self, results, minWidth=2):
width = []
for var in results["head"]["vars"]:
width.append(max(minWidth, len(var)+1))
width.append(max(minWidth, len(var) + 1))
for result in results["results"]["bindings"]:
index = 0
for var in results["head"]["vars"]:
Expand All @@ -1135,9 +1137,9 @@ def __get_prettyprint_string_sparql_var_result(self, result):
lang = result.get("xml:lang", None)
datatype = result.get("datatype", None)
if lang is not None:
value += "@"+lang
value += "@" + lang
if datatype is not None:
value += " ["+datatype+"]"
value += " [" + datatype + "]"
return value

def __str__(self):
Expand All @@ -1148,7 +1150,7 @@ def __str__(self):
.. versionadded:: 1.8.3
"""
fullname = self.__module__ + "." + self.__class__.__name__
str_requestedFormat = '"requestedFormat" : '+repr(self.requestedFormat)
str_requestedFormat = '"requestedFormat" : ' + repr(self.requestedFormat)
str_url = self.response.url
str_code = self.response.code
str_headers = self.response.info()
Expand Down
1 change: 1 addition & 0 deletions custom_fixers/fix_urllib2.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from lib2to3.fixer_base import BaseFix
from lib2to3.fixer_util import Name


class FixUrllib2(BaseFix):
PATTERN = "power< fixprefix='urllib2' trailer< '.' '_opener' > >|power< fixprefix='urllib2' trailer< '.' '_opener' > trailer< '.' handlers='handlers' > >"

Expand Down
44 changes: 23 additions & 21 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

try:
from ez_setup import use_setuptools

use_setuptools()
except:
pass
Expand All @@ -13,12 +14,14 @@

try:
import six

py3 = six.PY3
except:
py3 = sys.version_info[0] >= 3

# metadata
import re

_version_re = re.compile(r'__version__\s*=\s*"(.*)"')
_authors_re = re.compile(r'__authors__\s*=\s*"(.*)"')
_url_re = re.compile(r'__url__\s*=\s*"(.*)"')
Expand All @@ -41,23 +44,22 @@
with open('requirements.txt', 'r') as f:
_install_requires = [line.rstrip('\n') for line in f]


setup(
name = 'SPARQLWrapper',
version = version,
description = 'SPARQL Endpoint interface to Python',
long_description = 'This is a wrapper around a SPARQL service. It helps in creating the query URI and, possibly, convert the result into a more manageable format.',
license = 'W3C SOFTWARE NOTICE AND LICENSE',
author = authors,
url = url,
download_url = 'https://github.com/RDFLib/sparqlwrapper/releases',
platforms = ['any'],
packages = ['SPARQLWrapper'],
install_requires = _install_requires,
extras_require = {
name='SPARQLWrapper',
version=version,
description='SPARQL Endpoint interface to Python',
long_description='This is a wrapper around a SPARQL service. It helps in creating the query URI and, possibly, convert the result into a more manageable format.',
license='W3C SOFTWARE NOTICE AND LICENSE',
author=authors,
url=url,
download_url='https://github.com/RDFLib/sparqlwrapper/releases',
platforms=['any'],
packages=['SPARQLWrapper'],
install_requires=_install_requires,
extras_require={
'keepalive': ['keepalive>=0.5'],
},
classifiers = [
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: W3C License',
Expand All @@ -73,14 +75,14 @@
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords = ['python', 'sparql', 'rdf', 'rdflib'],
use_2to3 = True,
use_2to3_fixers = ['custom_fixers'],
project_urls={
],
keywords=['python', 'sparql', 'rdf', 'rdflib'],
use_2to3=True,
use_2to3_fixers=['custom_fixers'],
project_urls={
'Home': 'https://rdflib.github.io/sparqlwrapper/',
'Documentation': 'https://sparqlwrapper.readthedocs.io',
'Source': 'https://github.com/RDFLib/sparqlwrapper',
'Tracker': 'https://github.com/RDFLib/sparqlwrapper/issues',
}
}
)

0 comments on commit 00b0bf5

Please sign in to comment.