Skip to content

Commit 5fa63fb

Browse files
committed
Make the linter happier
1 parent a86989b commit 5fa63fb

File tree

1 file changed

+66
-37
lines changed

1 file changed

+66
-37
lines changed

astroquery/eso/core.py

Lines changed: 66 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@ class CalSelectorError(Exception):
4343
"""
4444

4545

46+
class UnknownException(Exception):
47+
"""
48+
Raised when an exception is not foreseen.
49+
"""
50+
51+
4652
class AuthInfo:
4753
def __init__(self, username: str, password: str, token: str):
4854
self.username = username
@@ -100,6 +106,26 @@ def __init__(self, timeout=None):
100106
def timeout(self):
101107
return self._timeout
102108

109+
# The logging module needs strings
110+
# written in %s style. This wrappers
111+
# are used for that purpose.
112+
# [W1203 - logging-fstring-interpolation]
113+
@staticmethod
114+
def log_info(message):
115+
log.info("%s", message)
116+
117+
@staticmethod
118+
def log_warning(message):
119+
log.warning("%s", message)
120+
121+
@staticmethod
122+
def log_error(message):
123+
log.error("%s", message)
124+
125+
@staticmethod
126+
def log_debug(message):
127+
log.debug("%s", message)
128+
103129
@timeout.setter
104130
def timeout(self, value):
105131
if hasattr(value, 'to'):
@@ -134,12 +160,12 @@ def from_cache(self, query_str, cache_timeout):
134160
if not isinstance(cached_table, Table):
135161
cached_table = None
136162
else:
137-
log.debug("Cache expired for %s ... ", table_file)
163+
self.log_debug(f"Cache expired for {table_file} ...")
138164
cached_table = None
139165
except FileNotFoundError:
140166
cached_table = None
141167
if cached_table:
142-
log.debug("Retrieved data from %s", table_file)
168+
self.log_debug(f"Retrieved data from {table_file} ...")
143169
return cached_table
144170

145171
def _authenticate(self, *, username: str, password: str) -> bool:
@@ -153,15 +179,15 @@ def _authenticate(self, *, username: str, password: str) -> bool:
153179
"client_secret": "clientSecret",
154180
"username": username,
155181
"password": password}
156-
log.info("Authenticating %s on 'www.eso.org' ...", username)
182+
self.log_info(f"Authenticating {username} on 'www.eso.org' ...")
157183
response = self._request('GET', self.AUTH_URL, params=url_params)
158184
if response.status_code == 200:
159185
token = json.loads(response.content)['id_token']
160186
self._auth_info = AuthInfo(username=username, password=password, token=token)
161-
log.info("Authentication successful!")
187+
self.log_info("Authentication successful!")
162188
return True
163189
else:
164-
log.error("Authentication failed!")
190+
self.log_error("Authentication failed!")
165191
return False
166192

167193
def _get_auth_info(self, username: str, *, store_password: bool = False,
@@ -214,7 +240,7 @@ def _login(self, *args, username: str = None, store_password: bool = False,
214240

215241
def _get_auth_header(self) -> Dict[str, str]:
216242
if self._auth_info and self._auth_info.expired():
217-
log.info("Authentication token has expired! Re-authenticating ...")
243+
self.log_info("Authentication token has expired! Re-authenticating ...")
218244
self._authenticate(username=self._auth_info.username,
219245
password=self._auth_info.password)
220246
if self._auth_info and not self._auth_info.expired():
@@ -249,7 +275,7 @@ def query_tap_service(self, query_str: str, cache: Optional[bool] = None) -> Opt
249275
except pyvo.dal.exceptions.DALQueryError as e:
250276
raise pyvo.dal.exceptions.DALQueryError(f"\n\n\
251277
Error executing the following query:\n\n{query_str}\n\n") from e
252-
except Exception as e:
278+
except UnknownException as e:
253279
raise RuntimeError(f"\n\n\
254280
Unknown exception {e} while executing the following query: \n\n{query_str}\n\n") from e
255281

@@ -342,7 +368,7 @@ def _query_instrument_or_collection(self,
342368
help_query = \
343369
f"select column_name, datatype from TAP_SCHEMA.columns where table_name = '{query_on.table_name}'"
344370
h = self.query_tap_service(help_query)
345-
log.info("Columns present in the table: %s", h)
371+
self.log_info(f"Columns present in the table: {h}")
346372
return
347373

348374
filters = {**dict(kwargs), **column_filters}
@@ -379,6 +405,7 @@ def query_instrument(self, instrument: Union[List, str] = None, *,
379405
column_filters: Dict = None, columns: Union[List, str] = None,
380406
open_form=False, print_help=False, cache=True,
381407
**kwargs) -> astropy.table.Table:
408+
_ = open_form
382409
return self._query_instrument_or_collection(query_on=QueryOnInstrument,
383410
primary_filter=instrument,
384411
column_filters=column_filters,
@@ -394,6 +421,7 @@ def query_collections(self, collections: Union[List, str] = None, *,
394421
**kwargs) -> astropy.table.Table:
395422
column_filters = column_filters or {}
396423
columns = columns or []
424+
_ = open_form
397425
return self._query_instrument_or_collection(query_on=QueryOnCollection,
398426
primary_filter=collections,
399427
column_filters=column_filters,
@@ -444,7 +472,7 @@ def query_main(self, *, column_filters=None, columns=None,
444472
help_query = \
445473
"select column_name, datatype from TAP_SCHEMA.columns where table_name = 'dbo.raw'"
446474
h = self.query_tap_service(help_query, cache=cache)
447-
log.info("Columns present in the table: %s", h)
475+
self.log_info(f"Columns present in the table: {h}")
448476
return
449477

450478
query = py2adql(table="dbo.raw",
@@ -543,7 +571,7 @@ def _find_cached_file(filename: str) -> bool:
543571
files_to_check.append(filename.rsplit(".", 1)[0])
544572
for file in files_to_check:
545573
if os.path.exists(file):
546-
log.info(f"Found cached file {file}")
574+
EsoClass.log_info(f"Found cached file {file}")
547575
return True
548576
return False
549577

@@ -557,7 +585,7 @@ def _download_eso_file(self, file_link: str, destination: str,
557585
filename = os.path.join(destination, filename)
558586
part_filename = filename + ".part"
559587
if os.path.exists(part_filename):
560-
log.info(f"Removing partially downloaded file {part_filename}")
588+
self.log_info(f"Removing partially downloaded file {part_filename}")
561589
os.remove(part_filename)
562590
download_required = overwrite or not self._find_cached_file(filename)
563591
if download_required:
@@ -573,23 +601,23 @@ def _download_eso_files(self, file_ids: List[str], destination: Optional[str],
573601
destination = os.path.abspath(destination)
574602
os.makedirs(destination, exist_ok=True)
575603
nfiles = len(file_ids)
576-
log.info(f"Downloading {nfiles} files ...")
604+
self.log_info(f"Downloading {nfiles} files ...")
577605
downloaded_files = []
578606
for i, file_id in enumerate(file_ids, 1):
579607
file_link = self.DOWNLOAD_URL + file_id
580-
log.info(f"Downloading file {i}/{nfiles} {file_link} to {destination}")
608+
self.log_info(f"Downloading file {i}/{nfiles} {file_link} to {destination}")
581609
try:
582610
filename, downloaded = self._download_eso_file(file_link, destination, overwrite)
583611
downloaded_files.append(filename)
584612
if downloaded:
585-
log.info(f"Successfully downloaded dataset {file_id} to {filename}")
613+
self.log_info(f"Successfully downloaded dataset {file_id} to {filename}")
586614
except requests.HTTPError as http_error:
587615
if http_error.response.status_code == 401:
588-
log.error(f"Access denied to {file_link}")
616+
self.log_error(f"Access denied to {file_link}")
589617
else:
590-
log.error(f"Failed to download {file_link}. {http_error}")
591-
except Exception as ex:
592-
log.error(f"Failed to download {file_link}. {ex}")
618+
self.log_error(f"Failed to download {file_link}. {http_error}")
619+
except RuntimeError as ex:
620+
self.log_error(f"Failed to download {file_link}. {ex}")
593621
return downloaded_files
594622

595623
def _unzip_file(self, filename: str) -> str:
@@ -602,12 +630,12 @@ def _unzip_file(self, filename: str) -> str:
602630
if filename.endswith(('fits.Z', 'fits.gz')):
603631
uncompressed_filename = filename.rsplit(".", 1)[0]
604632
if not os.path.exists(uncompressed_filename):
605-
log.info(f"Uncompressing file {filename}")
633+
self.log_info(f"Uncompressing file {filename}")
606634
try:
607635
subprocess.run([self.GUNZIP, filename], check=True)
608-
except Exception as ex:
636+
except UnknownException as ex:
609637
uncompressed_filename = None
610-
log.error(f"Failed to unzip {filename}: {ex}")
638+
self.log_error(f"Failed to unzip {filename}: {ex}")
611639
return uncompressed_filename or filename
612640

613641
def _unzip_files(self, files: List[str]) -> List[str]:
@@ -628,7 +656,7 @@ def _save_xml(self, payload: bytes, filename: str, destination: str):
628656
destination = os.path.abspath(destination)
629657
os.makedirs(destination, exist_ok=True)
630658
filename = os.path.join(destination, filename)
631-
log.info(f"Saving Calselector association tree to {filename}")
659+
self.log_info(f"Saving Calselector association tree to {filename}")
632660
with open(filename, "wb") as fd:
633661
fd.write(payload)
634662

@@ -685,7 +713,8 @@ def get_associated_files(self, datasets: List[str], *, mode: str = "raw",
685713

686714
@deprecated_renamed_argument(('request_all_objects', 'request_id'), (None, None),
687715
since=['0.4.7', '0.4.7'])
688-
def retrieve_data(self, datasets, *, continuation=False, destination=None, with_calib=None, unzip=True,
716+
def retrieve_data(self, datasets, *, continuation=False, destination=None,
717+
with_calib=None, unzip=True,
689718
request_all_objects=None, request_id=None):
690719
"""
691720
Retrieve a list of datasets form the ESO archive.
@@ -733,24 +762,24 @@ def retrieve_data(self, datasets, *, continuation=False, destination=None, with_
733762

734763
associated_files = []
735764
if with_calib:
736-
log.info(f"Retrieving associated '{with_calib}' calibration files ...")
765+
self.log_info(f"Retrieving associated '{with_calib}' calibration files ...")
737766
try:
738767
# batch calselector requests to avoid possible issues on the ESO server
739768
BATCH_SIZE = 100
740769
sorted_datasets = sorted(datasets)
741770
for i in range(0, len(sorted_datasets), BATCH_SIZE):
742771
associated_files += self.get_associated_files(sorted_datasets[i:i + BATCH_SIZE], mode=with_calib)
743772
associated_files = list(set(associated_files))
744-
log.info(f"Found {len(associated_files)} associated files")
745-
except Exception as ex:
746-
log.error(f"Failed to retrieve associated files: {ex}")
773+
self.log_info(f"Found {len(associated_files)} associated files")
774+
except UnknownException as ex:
775+
self.log_error(f"Failed to retrieve associated files: {ex}")
747776

748777
all_datasets = datasets + associated_files
749-
log.info("Downloading datasets ...")
778+
self.log_info("Downloading datasets ...")
750779
files = self._download_eso_files(all_datasets, destination, continuation)
751780
if unzip:
752781
files = self._unzip_files(files)
753-
log.info("Done!")
782+
self.log_info("Done!")
754783
return files[0] if files and len(files) == 1 and return_string else files
755784

756785
def _activate_form(self, response, *, form_index=0, form_id=None, inputs=None,
@@ -880,12 +909,12 @@ def _activate_form(self, response, *, form_index=0, form_id=None, inputs=None,
880909

881910
# for future debugging
882911
self._payload = payload
883-
log.debug("Form: payload={0}".format(payload))
912+
self.log_debug("Form: payload={0}".format(payload))
884913

885914
if method is not None:
886915
fmt = method
887916

888-
log.debug("Method/format = {0}".format(fmt))
917+
self.log_debug("Method/format = {0}".format(fmt))
889918

890919
# Send payload
891920
if fmt == 'get':
@@ -955,11 +984,11 @@ def _print_query_help(self, url, *, cache=True):
955984
"""
956985
Download a form and print it in a quasi-human-readable way
957986
"""
958-
log.info("List of accepted column_filters parameters.")
959-
log.info("The presence of a column in the result table can be "
960-
"controlled if prefixed with a [ ] checkbox.")
961-
log.info("The default columns in the result table are shown as "
962-
"already ticked: [x].")
987+
self.log_info("List of accepted column_filters parameters.")
988+
self.log_info("The presence of a column in the result table can be "
989+
+ "controlled if prefixed with a [ ] checkbox.")
990+
self.log_info("The default columns in the result table are shown as "
991+
+ "already ticked: [x].")
963992

964993
result_string = []
965994

@@ -1008,7 +1037,7 @@ def _print_query_help(self, url, *, cache=True):
10081037
result_string.append("{0} {1}: {2}"
10091038
.format(checkbox, name, value))
10101039

1011-
log.info("\n".join(result_string))
1040+
self.log_info("\n".join(result_string))
10121041
return result_string
10131042

10141043
@deprecated(since="v0.4.8", message=("The ESO list_surveys function is deprecated,"

0 commit comments

Comments
 (0)