@@ -43,6 +43,12 @@ class CalSelectorError(Exception):
43
43
"""
44
44
45
45
46
+ class UnknownException (Exception ):
47
+ """
48
+ Raised when an exception is not foreseen.
49
+ """
50
+
51
+
46
52
class AuthInfo :
47
53
def __init__ (self , username : str , password : str , token : str ):
48
54
self .username = username
@@ -100,6 +106,26 @@ def __init__(self, timeout=None):
100
106
def timeout (self ):
101
107
return self ._timeout
102
108
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
+
103
129
@timeout .setter
104
130
def timeout (self , value ):
105
131
if hasattr (value , 'to' ):
@@ -134,12 +160,12 @@ def from_cache(self, query_str, cache_timeout):
134
160
if not isinstance (cached_table , Table ):
135
161
cached_table = None
136
162
else :
137
- log . debug ( "Cache expired for %s ... " , table_file )
163
+ self . log_debug ( f "Cache expired for { table_file } ..." )
138
164
cached_table = None
139
165
except FileNotFoundError :
140
166
cached_table = None
141
167
if cached_table :
142
- log . debug ( "Retrieved data from %s" , table_file )
168
+ self . log_debug ( f "Retrieved data from { table_file } ..." )
143
169
return cached_table
144
170
145
171
def _authenticate (self , * , username : str , password : str ) -> bool :
@@ -153,15 +179,15 @@ def _authenticate(self, *, username: str, password: str) -> bool:
153
179
"client_secret" : "clientSecret" ,
154
180
"username" : username ,
155
181
"password" : password }
156
- log . info ( "Authenticating %s on 'www.eso.org' ..." , username )
182
+ self . log_info ( f "Authenticating { username } on 'www.eso.org' ..." )
157
183
response = self ._request ('GET' , self .AUTH_URL , params = url_params )
158
184
if response .status_code == 200 :
159
185
token = json .loads (response .content )['id_token' ]
160
186
self ._auth_info = AuthInfo (username = username , password = password , token = token )
161
- log . info ("Authentication successful!" )
187
+ self . log_info ("Authentication successful!" )
162
188
return True
163
189
else :
164
- log . error ("Authentication failed!" )
190
+ self . log_error ("Authentication failed!" )
165
191
return False
166
192
167
193
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,
214
240
215
241
def _get_auth_header (self ) -> Dict [str , str ]:
216
242
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 ..." )
218
244
self ._authenticate (username = self ._auth_info .username ,
219
245
password = self ._auth_info .password )
220
246
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
249
275
except pyvo .dal .exceptions .DALQueryError as e :
250
276
raise pyvo .dal .exceptions .DALQueryError (f"\n \n \
251
277
Error executing the following query:\n \n { query_str } \n \n " ) from e
252
- except Exception as e :
278
+ except UnknownException as e :
253
279
raise RuntimeError (f"\n \n \
254
280
Unknown exception { e } while executing the following query: \n \n { query_str } \n \n " ) from e
255
281
@@ -342,7 +368,7 @@ def _query_instrument_or_collection(self,
342
368
help_query = \
343
369
f"select column_name, datatype from TAP_SCHEMA.columns where table_name = '{ query_on .table_name } '"
344
370
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 } " )
346
372
return
347
373
348
374
filters = {** dict (kwargs ), ** column_filters }
@@ -379,6 +405,7 @@ def query_instrument(self, instrument: Union[List, str] = None, *,
379
405
column_filters : Dict = None , columns : Union [List , str ] = None ,
380
406
open_form = False , print_help = False , cache = True ,
381
407
** kwargs ) -> astropy .table .Table :
408
+ _ = open_form
382
409
return self ._query_instrument_or_collection (query_on = QueryOnInstrument ,
383
410
primary_filter = instrument ,
384
411
column_filters = column_filters ,
@@ -394,6 +421,7 @@ def query_collections(self, collections: Union[List, str] = None, *,
394
421
** kwargs ) -> astropy .table .Table :
395
422
column_filters = column_filters or {}
396
423
columns = columns or []
424
+ _ = open_form
397
425
return self ._query_instrument_or_collection (query_on = QueryOnCollection ,
398
426
primary_filter = collections ,
399
427
column_filters = column_filters ,
@@ -444,7 +472,7 @@ def query_main(self, *, column_filters=None, columns=None,
444
472
help_query = \
445
473
"select column_name, datatype from TAP_SCHEMA.columns where table_name = 'dbo.raw'"
446
474
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 } " )
448
476
return
449
477
450
478
query = py2adql (table = "dbo.raw" ,
@@ -543,7 +571,7 @@ def _find_cached_file(filename: str) -> bool:
543
571
files_to_check .append (filename .rsplit ("." , 1 )[0 ])
544
572
for file in files_to_check :
545
573
if os .path .exists (file ):
546
- log . info (f"Found cached file { file } " )
574
+ EsoClass . log_info (f"Found cached file { file } " )
547
575
return True
548
576
return False
549
577
@@ -557,7 +585,7 @@ def _download_eso_file(self, file_link: str, destination: str,
557
585
filename = os .path .join (destination , filename )
558
586
part_filename = filename + ".part"
559
587
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 } " )
561
589
os .remove (part_filename )
562
590
download_required = overwrite or not self ._find_cached_file (filename )
563
591
if download_required :
@@ -573,23 +601,23 @@ def _download_eso_files(self, file_ids: List[str], destination: Optional[str],
573
601
destination = os .path .abspath (destination )
574
602
os .makedirs (destination , exist_ok = True )
575
603
nfiles = len (file_ids )
576
- log . info (f"Downloading { nfiles } files ..." )
604
+ self . log_info (f"Downloading { nfiles } files ..." )
577
605
downloaded_files = []
578
606
for i , file_id in enumerate (file_ids , 1 ):
579
607
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 } " )
581
609
try :
582
610
filename , downloaded = self ._download_eso_file (file_link , destination , overwrite )
583
611
downloaded_files .append (filename )
584
612
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 } " )
586
614
except requests .HTTPError as http_error :
587
615
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 } " )
589
617
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 } " )
593
621
return downloaded_files
594
622
595
623
def _unzip_file (self , filename : str ) -> str :
@@ -602,12 +630,12 @@ def _unzip_file(self, filename: str) -> str:
602
630
if filename .endswith (('fits.Z' , 'fits.gz' )):
603
631
uncompressed_filename = filename .rsplit ("." , 1 )[0 ]
604
632
if not os .path .exists (uncompressed_filename ):
605
- log . info (f"Uncompressing file { filename } " )
633
+ self . log_info (f"Uncompressing file { filename } " )
606
634
try :
607
635
subprocess .run ([self .GUNZIP , filename ], check = True )
608
- except Exception as ex :
636
+ except UnknownException as ex :
609
637
uncompressed_filename = None
610
- log . error (f"Failed to unzip { filename } : { ex } " )
638
+ self . log_error (f"Failed to unzip { filename } : { ex } " )
611
639
return uncompressed_filename or filename
612
640
613
641
def _unzip_files (self , files : List [str ]) -> List [str ]:
@@ -628,7 +656,7 @@ def _save_xml(self, payload: bytes, filename: str, destination: str):
628
656
destination = os .path .abspath (destination )
629
657
os .makedirs (destination , exist_ok = True )
630
658
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 } " )
632
660
with open (filename , "wb" ) as fd :
633
661
fd .write (payload )
634
662
@@ -685,7 +713,8 @@ def get_associated_files(self, datasets: List[str], *, mode: str = "raw",
685
713
686
714
@deprecated_renamed_argument (('request_all_objects' , 'request_id' ), (None , None ),
687
715
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 ,
689
718
request_all_objects = None , request_id = None ):
690
719
"""
691
720
Retrieve a list of datasets form the ESO archive.
@@ -733,24 +762,24 @@ def retrieve_data(self, datasets, *, continuation=False, destination=None, with_
733
762
734
763
associated_files = []
735
764
if with_calib :
736
- log . info (f"Retrieving associated '{ with_calib } ' calibration files ..." )
765
+ self . log_info (f"Retrieving associated '{ with_calib } ' calibration files ..." )
737
766
try :
738
767
# batch calselector requests to avoid possible issues on the ESO server
739
768
BATCH_SIZE = 100
740
769
sorted_datasets = sorted (datasets )
741
770
for i in range (0 , len (sorted_datasets ), BATCH_SIZE ):
742
771
associated_files += self .get_associated_files (sorted_datasets [i :i + BATCH_SIZE ], mode = with_calib )
743
772
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 } " )
747
776
748
777
all_datasets = datasets + associated_files
749
- log . info ("Downloading datasets ..." )
778
+ self . log_info ("Downloading datasets ..." )
750
779
files = self ._download_eso_files (all_datasets , destination , continuation )
751
780
if unzip :
752
781
files = self ._unzip_files (files )
753
- log . info ("Done!" )
782
+ self . log_info ("Done!" )
754
783
return files [0 ] if files and len (files ) == 1 and return_string else files
755
784
756
785
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,
880
909
881
910
# for future debugging
882
911
self ._payload = payload
883
- log . debug ("Form: payload={0}" .format (payload ))
912
+ self . log_debug ("Form: payload={0}" .format (payload ))
884
913
885
914
if method is not None :
886
915
fmt = method
887
916
888
- log . debug ("Method/format = {0}" .format (fmt ))
917
+ self . log_debug ("Method/format = {0}" .format (fmt ))
889
918
890
919
# Send payload
891
920
if fmt == 'get' :
@@ -955,11 +984,11 @@ def _print_query_help(self, url, *, cache=True):
955
984
"""
956
985
Download a form and print it in a quasi-human-readable way
957
986
"""
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]." )
963
992
964
993
result_string = []
965
994
@@ -1008,7 +1037,7 @@ def _print_query_help(self, url, *, cache=True):
1008
1037
result_string .append ("{0} {1}: {2}"
1009
1038
.format (checkbox , name , value ))
1010
1039
1011
- log . info ("\n " .join (result_string ))
1040
+ self . log_info ("\n " .join (result_string ))
1012
1041
return result_string
1013
1042
1014
1043
@deprecated (since = "v0.4.8" , message = ("The ESO list_surveys function is deprecated,"
0 commit comments