Skip to content

Commit f2e6f19

Browse files
Merge pull request #58 from sentinel-hub/fix/pylint_errors
Fix pylint errors
2 parents bc496cf + c6e9510 commit f2e6f19

19 files changed

Lines changed: 209 additions & 101 deletions

SentinelHub/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def classFactory(iface):
3030
# pylint: disable=unused-import
3131

3232
# The following initializes UI
33-
from . import resources
33+
from . import resources # pylint: disable=import-self,no-name-in-module
3434
from .utils.meta import ensure_import
3535

3636
ensure_import("defusedxml")

SentinelHub/constants.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Module containing constants
33
"""
4+
45
from enum import Enum
56

67
from qgis.core import Qgis

SentinelHub/exceptions.py

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,67 @@
11
"""
22
Utilities for handling exceptions and error messaging
33
"""
4+
45
import time
56
from abc import ABC, abstractmethod
7+
from defusedxml import ElementTree
8+
import requests
69

710
from qgis.utils import iface
811

12+
from sentinelhub.client import get_proxy_from_qsettings
913
from .constants import ExtentType, MessageType
1014
from .utils.meta import PLUGIN_NAME
1115

1216

17+
def get_error_message(exception):
18+
"""Creates an error message from the given exception
19+
20+
:param exception: Exception obtained during download
21+
:type exception: requests.RequestException
22+
:return: error message
23+
:rtype: str
24+
"""
25+
message = f"{exception.__class__.__name__}: "
26+
27+
if isinstance(exception, (requests.ConnectionError, requests.Timeout)):
28+
if isinstance(exception, requests.ConnectionError):
29+
message += "Cannot access service, check your internet connection."
30+
else:
31+
message += "Connection timed out, service is too slow"
32+
33+
enabled, host, port, _, _ = get_proxy_from_qsettings()
34+
if enabled:
35+
message += f" QGIS is configured to use proxy: {host}"
36+
if port:
37+
message += f":{port}"
38+
39+
return message
40+
41+
if isinstance(exception, requests.HTTPError):
42+
try:
43+
server_message = ""
44+
for elem in ElementTree.fromstring(exception.response.content):
45+
if "ServiceException" in elem.tag:
46+
server_message += elem.text.strip("\n\t ")
47+
except ElementTree.ParseError:
48+
server_message = exception.response.text.strip("\n\t ")
49+
50+
server_message = server_message.encode("ascii", errors="ignore").decode("utf-8")
51+
52+
# Include HTTP status code
53+
status_code = exception.response.status_code
54+
message += f"HTTP {status_code} - "
55+
56+
# Provide meaningful message when server response is empty
57+
if not server_message:
58+
server_message = "No additional details provided by server"
59+
60+
return message + f"{server_message}"
61+
62+
return message + str(exception)
63+
64+
1365
def show_message(message, message_type):
1466
"""Show message for user
1567
@@ -192,7 +244,10 @@ def check(self, plugin):
192244
return True
193245

194246
return (
195-
plugin.settings.lat_min and plugin.settings.lat_max and plugin.settings.lng_min and plugin.settings.lng_max
247+
plugin.settings.lat_min
248+
and plugin.settings.lat_max
249+
and plugin.settings.lng_min
250+
and plugin.settings.lng_max
196251
)
197252

198253

SentinelHub/metadata.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ name=SentinelHub
66
qgisMinimumVersion=3.22
77
qgisMaximumVersion=4.99
88
description=SentinelHub plugin enables users to harness the power of Sentinel Hub services directly from QGIS.
9-
version=2.0.5
9+
version=2.0.6
1010
author=Sinergise
1111
email=info@sentinel-hub.com
1212

@@ -26,6 +26,8 @@ repository=https://github.com/sentinel-hub/sentinelhub-qgis-plugin
2626

2727
# Recommended items:
2828
changelog=
29+
2.0.6
30+
- Maintenance: linting fixes
2931
2.0.5
3032
- Use defusedxml for parsing XML responses to address security scanner findings
3133
2.0.4

SentinelHub/sentinelhub/client.py

Lines changed: 12 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,12 @@
22
Download client for Sentinel Hub service
33
"""
44

5-
from defusedxml import ElementTree
6-
75
import requests
86
import requests.auth
97
from qgis.PyQt.QtCore import QSettings
108

119
from ..constants import DEFAULT_REQUEST_TIMEOUT
12-
from ..exceptions import DownloadError
10+
from ..exceptions import DownloadError, get_error_message
1311
from ..utils.meta import get_plugin_version
1412
from .session import Session
1513

@@ -38,7 +36,9 @@ def download(self, url, timeout=DEFAULT_REQUEST_TIMEOUT, session_settings=None):
3836
proxy_dict, auth = get_proxy_config()
3937
headers = self._prepare_headers(session_settings)
4038
try:
41-
response = requests.get(url, headers=headers, timeout=timeout, proxies=proxy_dict, auth=auth)
39+
response = requests.get(
40+
url, headers=headers, timeout=timeout, proxies=proxy_dict, auth=auth
41+
)
4242
response.raise_for_status()
4343
except requests.RequestException as exception:
4444
raise DownloadError(get_error_message(exception)) from exception
@@ -63,61 +63,15 @@ def _get_session(settings):
6363
return Client._CACHED_SESSIONS[cache_key]
6464

6565
session = Session(
66-
base_url=settings.base_url, client_id=settings.client_id, client_secret=settings.client_secret
66+
base_url=settings.base_url,
67+
client_id=settings.client_id,
68+
client_secret=settings.client_secret,
6769
)
6870

6971
Client._CACHED_SESSIONS[cache_key] = session
7072
return session
7173

7274

73-
def get_error_message(exception):
74-
"""Creates an error message from the given exception
75-
76-
:param exception: Exception obtained during download
77-
:type exception: requests.RequestException
78-
:return: error message
79-
:rtype: str
80-
"""
81-
message = f"{exception.__class__.__name__}: "
82-
83-
if isinstance(exception, (requests.ConnectionError, requests.Timeout)):
84-
if isinstance(exception, requests.ConnectionError):
85-
message += "Cannot access service, check your internet connection."
86-
else:
87-
message += "Connection timed out, service is too slow"
88-
89-
enabled, host, port, _, _ = get_proxy_from_qsettings()
90-
if enabled:
91-
message += f" QGIS is configured to use proxy: {host}"
92-
if port:
93-
message += f":{port}"
94-
95-
return message
96-
97-
if isinstance(exception, requests.HTTPError):
98-
try:
99-
server_message = ""
100-
for elem in ElementTree.fromstring(exception.response.content):
101-
if "ServiceException" in elem.tag:
102-
server_message += elem.text.strip("\n\t ")
103-
except ElementTree.ParseError:
104-
server_message = exception.response.text.strip("\n\t ")
105-
106-
server_message = server_message.encode("ascii", errors="ignore").decode("utf-8")
107-
108-
# Include HTTP status code
109-
status_code = exception.response.status_code
110-
message += f"HTTP {status_code} - "
111-
112-
# Provide meaningful message when server response is empty
113-
if not server_message:
114-
server_message = "No additional details provided by server"
115-
116-
return message + f"{server_message}"
117-
118-
return message + str(exception)
119-
120-
12175
def get_proxy_config():
12276
"""Get proxy config from QSettings and builds proxy parameters
12377
@@ -132,7 +86,11 @@ def get_proxy_config():
13286
for protocol in ["http", "https", "ftp"]:
13387
proxy_dict[protocol] = f"{protocol}://{host}{port_str}"
13488

135-
auth = requests.auth.HTTPProxyAuth(user, password) if enabled and user and password else None
89+
auth = (
90+
requests.auth.HTTPProxyAuth(user, password)
91+
if enabled and user and password
92+
else None
93+
)
13694

13795
return proxy_dict, auth
13896

SentinelHub/sentinelhub/common.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ def load(cls, payload):
3636
elif "datasetSource" in payload:
3737
data_source_id = payload["datasetSource"]["@id"].rsplit("/", 1)[-1]
3838
else:
39-
raise ValueError("Layer payload missing both 'datasetSourceId' and 'datasetSource' fields")
39+
raise ValueError(
40+
"Layer payload missing both 'datasetSourceId' and 'datasetSource' fields"
41+
)
4042

4143
return cls(
4244
layer_id=payload["id"],
@@ -52,7 +54,14 @@ def load(cls, payload):
5254
class DataSource:
5355
"""Stores info about a Sentinel Hub data source"""
5456

55-
def __init__(self, data_source_type, data_source_id, collection_id=None, name=None, service_url=None):
57+
def __init__(
58+
self,
59+
data_source_type,
60+
data_source_id,
61+
collection_id=None,
62+
name=None,
63+
service_url=None,
64+
): # pylint: disable=too-many-positional-arguments
5665
self.type = data_source_type
5766
self.id = int(data_source_id)
5867
self.collection_id = collection_id

SentinelHub/sentinelhub/ogc.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Module with Sentinel Hub OGC utilities
33
"""
4+
45
import datetime as dt
56
from urllib.parse import quote_plus, urlencode
67

@@ -92,7 +93,7 @@ def get_wfs_url(settings, layer, bbox_str, time_range, maxcc=None):
9293
return _build_url(base_url, params)
9394

9495

95-
def get_wcs_url(settings, layer, bbox, crs=None):
96+
def get_wcs_url(settings, bbox, crs=None):
9697
"""Generate a URL for WCS request from parameters"""
9798
base_url = _get_service_endpoint(settings, ServiceType.WCS)
9899
params = {
@@ -147,7 +148,9 @@ def _build_uri(base_url, url_params, uri_params, use_builder=False):
147148

148149
def _build_time(settings):
149150
"""Builds a time string to be sent to Sentinel Hub service"""
150-
if (settings.is_exact_date and not settings.start_time) or (not settings.start_time and not settings.end_time):
151+
if (settings.is_exact_date and not settings.start_time) or (
152+
not settings.start_time and not settings.end_time
153+
):
151154
return ""
152155

153156
start_time = settings.start_time

SentinelHub/sentinelhub/session.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from qgis.core import QgsMessageLog
1111
from requests_oauthlib import OAuth2Session
1212

13-
from ..exceptions import SessionError
13+
from ..exceptions import SessionError, get_error_message
1414

1515

1616
class Session:
@@ -42,6 +42,7 @@ def __init__(self, base_url, client_id, client_secret):
4242

4343
@staticmethod
4444
def select_oauth_url(base_url):
45+
"""Selects the appropriate OAuth URL based on the base URL."""
4546
if base_url == "https://sh.dataspace.copernicus.eu":
4647
return "https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token"
4748
return f"{base_url}/oauth/token"
@@ -53,7 +54,10 @@ def token(self):
5354
:return: A token in a form of dictionary of parameters
5455
:rtype: dict
5556
"""
56-
if self._token and self._token["expires_at"] > time.time() + self.SECONDS_BEFORE_EXPIRY:
57+
if (
58+
self._token
59+
and self._token["expires_at"] > time.time() + self.SECONDS_BEFORE_EXPIRY
60+
):
5761
return self._token
5862

5963
self._token = self._fetch_token()
@@ -72,20 +76,24 @@ def _fetch_token(self):
7276
"""Collects a new token from Sentinel Hub service"""
7377
oauth_client = BackendApplicationClient(client_id=self.client_id)
7478

75-
QgsMessageLog.logMessage("Creating a new authentication session with Sentinel Hub service")
79+
QgsMessageLog.logMessage(
80+
"Creating a new authentication session with Sentinel Hub service"
81+
)
7682

7783
try:
7884
with OAuth2Session(client=oauth_client) as oauth_session:
7985
return oauth_session.fetch_token(
80-
token_url=self.oauth_url, client_id=self.client_id, client_secret=self.client_secret
86+
token_url=self.oauth_url,
87+
client_id=self.client_id,
88+
client_secret=self.client_secret,
8189
)
8290
except requests.HTTPError as exception:
83-
from ..sentinelhub.client import get_error_message
84-
8591
error_msg = get_error_message(exception)
8692
raise SessionError(error_msg) from exception
8793
except OAuth2Error as exception:
8894
error_details = str(exception)
8995
if error_details:
90-
raise SessionError(f"Authentication failed: {error_details}") from exception
96+
raise SessionError(
97+
f"Authentication failed: {error_details}"
98+
) from exception
9199
raise SessionError() from exception

SentinelHub/sentinelhub/wcs.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Utilities for interacting with Sentinel Hub WCS service
33
"""
4+
45
import os
56

67
from ..constants import CrsType, ExtentType
@@ -11,9 +12,13 @@
1112

1213
def download_wcs_image(settings, layer, bbox, client):
1314
"""Downloads and saves an image from Sentinel Hub WCS service"""
14-
crs = settings.crs if settings.download_extent_type is ExtentType.CURRENT else CrsType.WGS84
15+
crs = (
16+
settings.crs
17+
if settings.download_extent_type is ExtentType.CURRENT
18+
else CrsType.WGS84
19+
)
1520
bbox_str = bbox_to_string(bbox, crs)
16-
url = get_wcs_url(settings, layer, bbox_str, crs)
21+
url = get_wcs_url(settings, bbox_str, crs)
1722

1823
filename = get_filename(settings, layer, bbox_str)
1924
path = os.path.join(settings.download_folder, filename)

SentinelHub/settings.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
"""
22
Module containing parameters and settings for Sentinel Hub services
33
"""
4+
45
import copy
56

67
from qgis.PyQt.QtCore import QSettings
78

8-
from .constants import CrsType, ExtentType, ImageFormat, ImagePriority, ServiceType, TimeType
9+
from .constants import (
10+
CrsType,
11+
ExtentType,
12+
ImageFormat,
13+
ImagePriority,
14+
ServiceType,
15+
TimeType,
16+
)
917

1018

1119
class Settings:
@@ -107,4 +115,5 @@ def copy(self):
107115
return copy.copy(self)
108116

109117
def clear(self):
118+
"""Clears all settings from the local store and from the instance"""
110119
self.qsettings.clear()

0 commit comments

Comments
 (0)