From 00b0bf56b04b2865f809d16e8e46d49c111c743f Mon Sep 17 00:00:00 2001 From: Carlos Tejo Date: Sun, 22 Mar 2020 10:34:18 +0100 Subject: [PATCH] fixed some identantion issue based on contribution from #143 --- SPARQLWrapper/KeyCaseInsensitiveDict.py | 1 + SPARQLWrapper/SPARQLExceptions.py | 3 ++ SPARQLWrapper/SmartWrapper.py | 7 ++-- SPARQLWrapper/Wrapper.py | 46 +++++++++++++------------ custom_fixers/fix_urllib2.py | 1 + setup.py | 44 ++++++++++++----------- 6 files changed, 56 insertions(+), 46 deletions(-) diff --git a/SPARQLWrapper/KeyCaseInsensitiveDict.py b/SPARQLWrapper/KeyCaseInsensitiveDict.py index ab59f53..cf3d271 100644 --- a/SPARQLWrapper/KeyCaseInsensitiveDict.py +++ b/SPARQLWrapper/KeyCaseInsensitiveDict.py @@ -19,6 +19,7 @@ :license: `W3C® Software notice and license `_ """ + class KeyCaseInsensitiveDict(dict): """ A simple implementation of a key case-insensitive dictionary diff --git a/SPARQLWrapper/SPARQLExceptions.py b/SPARQLWrapper/SPARQLExceptions.py index 3bf6397..b811248 100644 --- a/SPARQLWrapper/SPARQLExceptions.py +++ b/SPARQLWrapper/SPARQLExceptions.py @@ -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``. @@ -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``. @@ -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``. diff --git a/SPARQLWrapper/SmartWrapper.py b/SPARQLWrapper/SmartWrapper.py index fc4493e..c6bfb97 100644 --- a/SPARQLWrapper/SmartWrapper.py +++ b/SPARQLWrapper/SmartWrapper.py @@ -26,6 +26,7 @@ ###################################################################################### + class Value(object): """ Class encapsulating a single binding for a variable. @@ -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: @@ -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: diff --git a/SPARQLWrapper/Wrapper.py b/SPARQLWrapper/Wrapper.py index 6d1af07..76df41c 100644 --- a/SPARQLWrapper/Wrapper.py +++ b/SPARQLWrapper/Wrapper.py @@ -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. @@ -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: @@ -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 @@ -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 = ( @@ -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) @@ -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: @@ -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: @@ -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). @@ -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): @@ -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): @@ -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. @@ -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) @@ -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 @@ -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"]: @@ -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): @@ -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() diff --git a/custom_fixers/fix_urllib2.py b/custom_fixers/fix_urllib2.py index cb77426..d17afe0 100755 --- a/custom_fixers/fix_urllib2.py +++ b/custom_fixers/fix_urllib2.py @@ -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' > >" diff --git a/setup.py b/setup.py index 4adef0f..be45ccc 100755 --- a/setup.py +++ b/setup.py @@ -5,6 +5,7 @@ try: from ez_setup import use_setuptools + use_setuptools() except: pass @@ -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*"(.*)"') @@ -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', @@ -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', - } + } )