31
31
from ..exceptions import RemoteServiceError , NoResultsWarning , LoginError
32
32
from ..query import QueryWithLogin
33
33
from ..utils import schema
34
- from .utils import py2adql , _split_str_as_list_of_str , sanitize_val , to_cache , hash , _check_response
34
+ from .utils import py2adql , _split_str_as_list_of_str , sanitize_val , to_cache , eso_hash
35
35
import pyvo
36
36
37
37
__doctest_skip__ = ['EsoClass.*' ]
@@ -41,7 +41,6 @@ class CalSelectorError(Exception):
41
41
"""
42
42
Raised on failure to parse CalSelector's response.
43
43
"""
44
- pass
45
44
46
45
47
46
class AuthInfo :
@@ -94,6 +93,8 @@ def __init__(self, timeout=None):
94
93
self ._auth_info : Optional [AuthInfo ] = None
95
94
self .timeout = timeout
96
95
self ._hash = None
96
+ # for future debugging
97
+ self ._payload = None
97
98
98
99
@property
99
100
def timeout (self ):
@@ -114,7 +115,7 @@ def tap_url() -> str:
114
115
return url
115
116
116
117
def request_file (self , query_str : str ):
117
- h = hash (query_str = query_str , url = self .tap_url ())
118
+ h = eso_hash (query_str = query_str , url = self .tap_url ())
118
119
fn = self .cache_location .joinpath (h + ".pickle" )
119
120
return fn
120
121
@@ -133,12 +134,12 @@ def from_cache(self, query_str, cache_timeout):
133
134
if not isinstance (cached_table , Table ):
134
135
cached_table = None
135
136
else :
136
- log .debug (f "Cache expired for { table_file } ..." )
137
+ log .debug ("Cache expired for %s ... " , table_file )
137
138
cached_table = None
138
139
except FileNotFoundError :
139
140
cached_table = None
140
141
if cached_table :
141
- log .debug ("Retrieved data from {0}" . format ( table_file ) )
142
+ log .debug ("Retrieved data from %s" , table_file )
142
143
return cached_table
143
144
144
145
def _authenticate (self , * , username : str , password : str ) -> bool :
@@ -152,7 +153,7 @@ def _authenticate(self, *, username: str, password: str) -> bool:
152
153
"client_secret" : "clientSecret" ,
153
154
"username" : username ,
154
155
"password" : password }
155
- log .info (f "Authenticating { username } on 'www.eso.org' ..." )
156
+ log .info ("Authenticating %s on 'www.eso.org' ..." , username )
156
157
response = self ._request ('GET' , self .AUTH_URL , params = url_params )
157
158
if response .status_code == 200 :
158
159
token = json .loads (response .content )['id_token' ]
@@ -187,8 +188,8 @@ def _get_auth_info(self, username: str, *, store_password: bool = False,
187
188
188
189
return username , password
189
190
190
- def _login (self , * , username : str = None , store_password : bool = False ,
191
- reenter_password : bool = False ) -> bool :
191
+ def _login (self , * args , username : str = None , store_password : bool = False ,
192
+ reenter_password : bool = False , ** kwargs ) -> bool :
192
193
"""
193
194
Login to the ESO User Portal.
194
195
@@ -221,7 +222,7 @@ def _get_auth_header(self) -> Dict[str, str]:
221
222
else :
222
223
return {}
223
224
224
- def _query_tap_service (self , query_str : str , cache : Optional [bool ] = None ) -> Optional [astropy .table .Table ]:
225
+ def query_tap_service (self , query_str : str , cache : Optional [bool ] = None ) -> Optional [astropy .table .Table ]:
225
226
"""
226
227
returns an astropy.table.Table from an adql query string
227
228
Example use:
@@ -245,10 +246,12 @@ def _query_tap_service(self, query_str: str, cache: Optional[bool] = None) -> Op
245
246
table_to_return = tap .search (query_str ).to_table ()
246
247
to_cache (table_to_return , self .request_file (query_str = query_str ))
247
248
248
- except pyvo .dal .exceptions .DALQueryError :
249
- raise pyvo .dal .exceptions .DALQueryError (f"\n \n Error executing the following query:\n \n { query_str } \n \n " )
249
+ except pyvo .dal .exceptions .DALQueryError as e :
250
+ raise pyvo .dal .exceptions .DALQueryError (f"\n \n \
251
+ Error executing the following query:\n \n { query_str } \n \n " ) from e
250
252
except Exception as e :
251
- raise Exception (f"\n \n Unknown exception { e } while executing the following query: \n \n { query_str } \n \n " )
253
+ raise RuntimeError (f"\n \n \
254
+ Unknown exception { e } while executing the following query: \n \n { query_str } \n \n " ) from e
252
255
253
256
if len (table_to_return ) > 0 :
254
257
return table_to_return
@@ -269,7 +272,7 @@ def list_instruments(self, *, cache=True) -> List[str]:
269
272
if self ._instruments is None :
270
273
self ._instruments = []
271
274
query_str = "select table_name from TAP_SCHEMA.tables where schema_name='ist' order by table_name"
272
- res = self ._query_tap_service (query_str )["table_name" ].data
275
+ res = self .query_tap_service (query_str , cache = cache )["table_name" ].data
273
276
self ._instruments = list (map (lambda x : x .split ("." )[1 ], res ))
274
277
return self ._instruments
275
278
@@ -288,15 +291,15 @@ def list_collections(self, *, cache=True) -> List[str]:
288
291
c = QueryOnCollection .column_name
289
292
t = QueryOnCollection .table_name
290
293
query_str = f"select distinct { c } from { t } "
291
- res = self ._query_tap_service (query_str )[c ].data
294
+ res = self .query_tap_service (query_str , cache = cache )[c ].data
292
295
293
296
self ._collections = list (res )
294
297
return self ._collections
295
298
296
299
def _query_instrument_or_collection (self ,
297
300
query_on : QueryOnField , primary_filter : Union [List [str ], str ], * ,
298
301
column_filters : Dict = None ,
299
- columns : Union [List , str ] = None , help = False , cache = True ,
302
+ columns : Union [List , str ] = None , print_help = False , cache = True ,
300
303
** kwargs ) -> astropy .table .Table :
301
304
"""
302
305
Query instrument- or collection-specific data contained in the ESO archive.
@@ -335,18 +338,18 @@ def _query_instrument_or_collection(self,
335
338
columns = columns or []
336
339
337
340
# TODO - move help printing to its own function
338
- if help :
341
+ if print_help :
339
342
help_query = \
340
343
f"select column_name, datatype from TAP_SCHEMA.columns where table_name = '{ query_on .table_name } '"
341
- h = self ._query_tap_service (help_query )
342
- log .info (f "Columns present in the table: { h } " )
344
+ h = self .query_tap_service (help_query )
345
+ log .info ("Columns present in the table: %s" , h )
343
346
return
344
347
345
348
filters = {** dict (kwargs ), ** column_filters }
346
349
c_size = 0.1775 # so that even HARPS fits to pass the tests
347
350
if 'box' in filters .keys ():
348
351
# TODO make c_size a parameter
349
- c_size = c_size
352
+ # c_size = c_size
350
353
del filters ['box' ]
351
354
if isinstance (primary_filter , str ):
352
355
primary_filter = _split_str_as_list_of_str (primary_filter )
@@ -369,38 +372,38 @@ def _query_instrument_or_collection(self,
369
372
query = py2adql (table = query_on .table_name , columns = columns , where_constraints = where_constraints ,
370
373
top = self .ROW_LIMIT )
371
374
372
- return self ._query_tap_service (query_str = query , cache = cache )
375
+ return self .query_tap_service (query_str = query , cache = cache )
373
376
374
377
@deprecated_renamed_argument (old_name = 'open_form' , new_name = None , since = '0.4.8' )
375
378
def query_instrument (self , instrument : Union [List , str ] = None , * ,
376
379
column_filters : Dict = None , columns : Union [List , str ] = None ,
377
- open_form = False , help = False , cache = True ,
380
+ open_form = False , print_help = False , cache = True ,
378
381
** kwargs ) -> astropy .table .Table :
379
382
return self ._query_instrument_or_collection (query_on = QueryOnInstrument ,
380
383
primary_filter = instrument ,
381
384
column_filters = column_filters ,
382
385
columns = columns ,
383
- help = help ,
386
+ print_help = print_help ,
384
387
cache = cache ,
385
388
** kwargs )
386
389
387
390
@deprecated_renamed_argument (old_name = 'open_form' , new_name = None , since = '0.4.8' )
388
391
def query_collections (self , collections : Union [List , str ] = None , * ,
389
392
column_filters : Dict = None , columns : Union [List , str ] = None ,
390
- open_form = False , help = False , cache = True ,
393
+ open_form = False , print_help = False , cache = True ,
391
394
** kwargs ) -> astropy .table .Table :
392
395
column_filters = column_filters or {}
393
396
columns = columns or []
394
397
return self ._query_instrument_or_collection (query_on = QueryOnCollection ,
395
398
primary_filter = collections ,
396
399
column_filters = column_filters ,
397
400
columns = columns ,
398
- help = help ,
401
+ print_help = print_help ,
399
402
cache = cache ,
400
403
** kwargs )
401
404
402
- def query_main (self , * , column_filters = {} , columns = [] ,
403
- open_form = False , help = False , cache = True , ** kwargs ):
405
+ def query_main (self , * , column_filters = None , columns = None ,
406
+ print_help = False , cache = True , ** kwargs ):
404
407
"""
405
408
Query raw data contained in the ESO archive.
406
409
@@ -437,12 +440,19 @@ def query_main(self, *, column_filters={}, columns=[],
437
440
where_constraints_strlist = [f"{ k } = { sanitize_val (v )} " for k , v in filters .items ()]
438
441
where_constraints = where_constraints_strlist
439
442
443
+ if print_help :
444
+ help_query = \
445
+ "select column_name, datatype from TAP_SCHEMA.columns where table_name = 'dbo.raw'"
446
+ h = self .query_tap_service (help_query , cache = cache )
447
+ log .info ("Columns present in the table: %s" , h )
448
+ return
449
+
440
450
query = py2adql (table = "dbo.raw" ,
441
451
columns = columns ,
442
452
where_constraints = where_constraints ,
443
453
top = self .ROW_LIMIT )
444
454
445
- return self ._query_tap_service (query_str = query )
455
+ return self .query_tap_service (query_str = query )
446
456
447
457
def get_headers (self , product_ids , * , cache = True ):
448
458
"""
@@ -572,8 +582,7 @@ def _download_eso_files(self, file_ids: List[str], destination: Optional[str],
572
582
filename , downloaded = self ._download_eso_file (file_link , destination , overwrite )
573
583
downloaded_files .append (filename )
574
584
if downloaded :
575
- log .info (f"Successfully downloaded dataset"
576
- f" { file_id } to { filename } " )
585
+ log .info (f"Successfully downloaded dataset { file_id } to { filename } " )
577
586
except requests .HTTPError as http_error :
578
587
if http_error .response .status_code == 401 :
579
588
log .error (f"Access denied to { file_link } " )
@@ -674,9 +683,10 @@ def get_associated_files(self, datasets: List[str], *, mode: str = "raw",
674
683
# remove input datasets from calselector results
675
684
return list (associated_files .difference (set (datasets )))
676
685
677
- @deprecated_renamed_argument (('request_all_objects' , 'request_id' ), (None , None ), since = ['0.4.7' , '0.4.7' ])
678
- def retrieve_data (self , datasets , * , continuation = False , destination = None , with_calib = None ,
679
- request_all_objects = False , unzip = True , request_id = None ):
686
+ @deprecated_renamed_argument (('request_all_objects' , 'request_id' ), (None , None ),
687
+ since = ['0.4.7' , '0.4.7' ])
688
+ def retrieve_data (self , datasets , * , continuation = False , destination = None , with_calib = None , unzip = True ,
689
+ request_all_objects = None , request_id = None ):
680
690
"""
681
691
Retrieve a list of datasets form the ESO archive.
682
692
@@ -711,6 +721,7 @@ def retrieve_data(self, datasets, *, continuation=False, destination=None, with_
711
721
>>> files = Eso.retrieve_data(dpids)
712
722
713
723
"""
724
+ _ = request_all_objects , request_id
714
725
return_string = False
715
726
if isinstance (datasets , str ):
716
727
return_string = True
@@ -742,14 +753,15 @@ def retrieve_data(self, datasets, *, continuation=False, destination=None, with_
742
753
log .info ("Done!" )
743
754
return files [0 ] if files and len (files ) == 1 and return_string else files
744
755
745
- def _activate_form (self , response , * , form_index = 0 , form_id = None , inputs = {} ,
756
+ def _activate_form (self , response , * , form_index = 0 , form_id = None , inputs = None ,
746
757
cache = True , method = None ):
747
758
"""
748
759
Parameters
749
760
----------
750
761
method: None or str
751
762
Can be used to override the form-specified method
752
763
"""
764
+ inputs = inputs or {}
753
765
# Extract form from response
754
766
root = BeautifulSoup (response .content , 'html5lib' )
755
767
if form_id is None :
@@ -776,7 +788,7 @@ def _activate_form(self, response, *, form_index=0, form_id=None, inputs={},
776
788
elif form .attrs ['enctype' ] == 'application/x-www-form-urlencoded' :
777
789
fmt = 'application/x-www-form-urlencoded' # post(url, data=payload)
778
790
else :
779
- raise Exception ("enctype={0} is not supported!" .format (form .attrs ['enctype' ]))
791
+ raise RuntimeError ("enctype={0} is not supported!" .format (form .attrs ['enctype' ]))
780
792
else :
781
793
fmt = 'application/x-www-form-urlencoded' # post(url, data=payload)
782
794
# Extract payload from form
@@ -885,7 +897,7 @@ def _activate_form(self, response, *, form_index=0, form_id=None, inputs={},
885
897
886
898
return response
887
899
888
- def query_apex_quicklooks (self , * , project_id = None , help = False ,
900
+ def query_apex_quicklooks (self , * , project_id = None , print_help = False ,
889
901
open_form = False , cache = True , ** kwargs ):
890
902
"""
891
903
APEX data are distributed with quicklook products identified with a
@@ -903,8 +915,9 @@ def query_apex_quicklooks(self, *, project_id=None, help=False,
903
915
table = None
904
916
if open_form :
905
917
webbrowser .open (apex_query_url )
906
- elif help :
907
- return self ._print_instrument_help (apex_query_url , 'apex' )
918
+ elif print_help :
919
+ # TODO: print some sensible help message
920
+ return "No help available for apex at the moment."
908
921
else :
909
922
910
923
payload = {'wdbo' : 'csv/download' }
@@ -918,7 +931,7 @@ def query_apex_quicklooks(self, *, project_id=None, help=False,
918
931
cache = cache , method = 'application/x-www-form-urlencoded' )
919
932
920
933
content = apex_response .content
921
- if _check_response ( content ) :
934
+ if content :
922
935
# First line is always garbage
923
936
content = content .split (b'\n ' , 1 )[1 ]
924
937
try :
@@ -967,31 +980,31 @@ def _print_query_help(self, url, *, cache=True):
967
980
checkbox_name = ""
968
981
checkbox_value = ""
969
982
for tag in section .next_siblings :
970
- if tag .name == u "table" :
983
+ if tag .name == "table" :
971
984
break
972
- elif tag .name == u "input" :
973
- if tag .get (u 'type' ) == u "checkbox" :
985
+ elif tag .name == "input" :
986
+ if tag .get ('type' ) == "checkbox" :
974
987
checkbox_name = tag ['name' ]
975
- checkbox_value = u "[x]" if ('checked' in tag .attrs ) else u "[ ]"
988
+ checkbox_value = "[x]" if ('checked' in tag .attrs ) else "[ ]"
976
989
name = ""
977
990
value = ""
978
991
else :
979
992
name = tag ['name' ]
980
993
value = ""
981
- elif tag .name == u "select" :
994
+ elif tag .name == "select" :
982
995
options = []
983
996
for option in tag .select ("option" ):
984
997
options += ["{0} ({1})" .format (option ['value' ], "" .join (option .stripped_strings ))]
985
- name = tag [u "name" ]
998
+ name = tag ["name" ]
986
999
value = ", " .join (options )
987
1000
else :
988
1001
name = ""
989
1002
value = ""
990
- if u "tab_" + name == checkbox_name :
1003
+ if "tab_" + name == checkbox_name :
991
1004
checkbox = checkbox_value
992
1005
else :
993
1006
checkbox = " "
994
- if name != u "" :
1007
+ if name != "" :
995
1008
result_string .append ("{0} {1}: {2}"
996
1009
.format (checkbox , name , value ))
997
1010
0 commit comments