Skip to content

Commit d60842b

Browse files
committed
refactor to use basequery's _request and to use async_to_sync instead of
duplicating code admittedly, this results in slightly less coherent docstrings, but it helps reduce code duplication, which is perhaps more important. Tests still pass!
1 parent 0130d9a commit d60842b

File tree

2 files changed

+43
-97
lines changed

2 files changed

+43
-97
lines changed

astroquery/lcogt/core.py

Lines changed: 39 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -79,38 +79,19 @@
7979
import astropy.io.votable as votable
8080

8181
from ..query import BaseQuery
82-
from ..utils import commons
82+
from ..utils import commons, async_to_sync
8383
from . import conf
8484
from ..exceptions import TableParseError
8585

8686
__all__ = ['Lcogt', 'LcogtClass']
8787

8888

89+
@async_to_sync
8990
class LcogtClass(BaseQuery):
9091
LCOGT_URL = conf.server
9192
TIMEOUT = conf.timeout
9293
ROW_LIMIT = conf.row_limit
93-
94-
def query_object(self, objstr, catalog=None, verbose=False):
95-
"""
96-
Queries the LCOGT public archive hosted at NASA/IPAC archive on target name
97-
and returns the result as a `~astropy.table.Table`.
98-
See examples below.
99-
100-
Parameters
101-
----------
102-
objstr : str
103-
name of object to be queried
104-
catalog : str
105-
name of the catalog to use. 'lco_img' for image meta data; 'lco_cat' for photometry.
106-
107-
Returns
108-
-------
109-
table : `~astropy.table.Table`
110-
Query results table
111-
"""
112-
response = self.query_object_async(objstr, catalog=catalog)
113-
return self._parse_result(response, verbose=verbose)
94+
catalogs = ['lco_img', 'lco_cat']
11495

11596
def query_object_async(self, objstr, catalog=None):
11697
"""
@@ -121,78 +102,30 @@ def query_object_async(self, objstr, catalog=None):
121102
----------
122103
objstr : str
123104
name of object to be queried
105+
catalog : str
106+
name of the catalog to use. 'lco_img' for image meta data;
107+
'lco_cat' for photometry.
124108
125109
Returns
126110
-------
127111
response : `requests.Response`
128112
Response of the query from the server
129113
"""
130114
if catalog is None:
131-
raise Exception("Catalogue name is required!")
115+
raise ValueError("Catalogue name is required!")
116+
if catalog not in self.catalogs:
117+
raise ValueError("Catalog name must be one of {0}"
118+
.format(self.catalogs))
119+
132120
request_payload = self._args_to_payload(catalog)
133121
request_payload['objstr'] = objstr
134-
response = commons.send_request(Lcogt.LCOGT_URL, request_payload,
135-
Lcogt.TIMEOUT, request_type='GET')
122+
response = self._request(method='GET', url=self.LCOGT_URL,
123+
params=request_payload, timeout=self.TIMEOUT)
136124
return response
137125

138-
def query_region(self, coordinates=None, catalog=None, spatial=None, radius=None, width=None, polygon=None,
139-
get_query_payload=False, verbose=False):
140-
"""
141-
This function can be used to perform either cone, box, polygon or
142-
all-sky search in the LCOGT public archive hosted by the NASA/IPAC Archive.
143-
144-
Parameters
145-
----------
146-
coordinates : str, `astropy.coordinates` object
147-
Gives the position of the center of the cone or box if
148-
performing a cone or box search. The string can give coordinates
149-
in various coordinate systems, or the name of a source that will
150-
be resolved on the server (see `here
151-
<http://irsa.ipac.caltech.edu/search_help.html>`_ for more
152-
details). Required if spatial is ``'Cone'`` or ``'Box'``. Optional
153-
if spatial is ``'Polygon'``.
154-
catalog : str
155-
The catalog to be used. Either ``lco_img`` for image metadata or ``lco_cat``
156-
for photometry.
157-
spatial : str
158-
Type of spatial query: ``'Cone'``, ``'Box'``, ``'Polygon'``, and
159-
``'All-Sky'``. If missing then defaults to ``'Cone'``.
160-
radius : str or `~astropy.units.Quantity` object, [optional for spatial is ``'Cone'``]
161-
The string must be parsable by `~astropy.coordinates.Angle`. The
162-
appropriate `~astropy.units.Quantity` object from
163-
`astropy.units` may also be used. Defaults to 10 arcsec.
164-
width : str, `~astropy.units.Quantity` object [Required for spatial is ``'Polygon'``.]
165-
166-
The string must be parsable by `~astropy.coordinates.Angle`. The
167-
appropriate `~astropy.units.Quantity` object from `astropy.units`
168-
may also be used.
169-
polygon : list, [Required for spatial is ``'Polygon'``]
170-
A list of ``(ra, dec)`` pairs (as tuples), in decimal degrees,
171-
outlinining the polygon to search in. It can also be a list of
172-
`astropy.coordinates` object or strings that can be parsed by
173-
`astropy.coordinates.ICRS`.
174-
get_query_payload : bool, optional
175-
If `True` then returns the dictionary sent as the HTTP request.
176-
Defaults to `False`.
177-
verbose : bool, optional.
178-
If `True` then displays warnings when the returned VOTable does not
179-
conform to the standard. Defaults to `False`.
180-
181-
Returns
182-
-------
183-
table : `~astropy.table.Table`
184-
A table containing the results of the query
185-
"""
186-
response = self.query_region_async(coordinates, catalog=catalog,
187-
spatial=spatial, radius=radius,
188-
width=width, polygon=polygon,
189-
get_query_payload=get_query_payload)
190-
if get_query_payload:
191-
return response
192-
return self._parse_result(response, verbose=verbose)
193126

194127
def query_region_async(self, coordinates=None, catalog=None,
195-
spatial='Cone', radius=10 * u.arcsec, width=None,
128+
spatial='Cone', radius=10*u.arcsec, width=None,
196129
polygon=None, get_query_payload=False):
197130
"""
198131
This function serves the same purpose as
@@ -210,16 +143,18 @@ def query_region_async(self, coordinates=None, catalog=None,
210143
details). Required if spatial is ``'Cone'`` or ``'Box'``. Optional
211144
if spatial is ``'Polygon'``.
212145
catalog : str
213-
The catalog to be used. Either ``'lco_img'`` for image metadata or ``'lco_cat'``
214-
for photometry.
146+
The catalog to be used. Either ``'lco_img'`` for image metadata or
147+
``'lco_cat'`` for photometry.
215148
spatial : str
216149
Type of spatial query: ``'Cone'``, ``'Box'``, ``'Polygon'``, and
217150
``'All-Sky'``. If missing then defaults to ``'Cone'``.
218-
radius : str or `~astropy.units.Quantity` object, [optional for spatial is ``'Cone'``]
151+
radius : str or `~astropy.units.Quantity` object, [optional for \\
152+
spatial is ``'Cone'``]
219153
The string must be parsable by `~astropy.coordinates.Angle`. The
220154
appropriate `~astropy.units.Quantity` object from
221155
`astropy.units` may also be used. Defaults to 10 arcsec.
222-
width : str, `~astropy.units.Quantity` object [Required for spatial is ``'Polygon'``.]
156+
width : str, `~astropy.units.Quantity` object [Required for spatial \\
157+
is ``'Polygon'``.]
223158
The string must be parsable by `~astropy.coordinates.Angle`. The
224159
appropriate `~astropy.units.Quantity` object from `astropy.units`
225160
may also be used.
@@ -238,7 +173,11 @@ def query_region_async(self, coordinates=None, catalog=None,
238173
The HTTP response returned from the service
239174
"""
240175
if catalog is None:
241-
raise Exception("Catalogue name is required!")
176+
raise ValueError("Catalogue name is required!")
177+
if catalog not in self.catalogs:
178+
raise ValueError("Catalog name must be one of {0}"
179+
.format(self.catalogs))
180+
242181

243182
request_payload = self._args_to_payload(catalog)
244183
request_payload.update(self._parse_spatial(spatial=spatial,
@@ -248,8 +187,8 @@ def query_region_async(self, coordinates=None, catalog=None,
248187

249188
if get_query_payload:
250189
return request_payload
251-
response = commons.send_request(Lcogt.LCOGT_URL, request_payload,
252-
Lcogt.TIMEOUT, request_type='GET')
190+
response = self._request(method='GET', url=self.LCOGT_URL,
191+
params=request_payload, timeout=self.TIMEOUT)
253192
return response
254193

255194
def _parse_spatial(self, spatial, coordinates, radius=None, width=None,
@@ -307,15 +246,20 @@ def _parse_spatial(self, spatial, coordinates, radius=None, width=None,
307246
request_payload['size'] = width.to(u.arcsec).value
308247
elif spatial == 'Polygon':
309248
if coordinates is not None:
310-
request_payload['objstr'] = coordinates if not commons._is_coordinate(coordinates) else _parse_coordinates(coordinates)
249+
request_payload['objstr'] = (coordinates if not
250+
commons._is_coordinate(coordinates)
251+
else
252+
_parse_coordinates(coordinates))
311253
try:
312254
coordinates_list = [_parse_coordinates(c) for c in polygon]
313255
except (ValueError, TypeError):
314-
coordinates_list = [_format_decimal_coords(*_pair_to_deg(pair)) for pair in polygon]
256+
coordinates_list = [_format_decimal_coords(*_pair_to_deg(pair))
257+
for pair in polygon]
315258
request_payload['polygon'] = ','.join(coordinates_list)
316259
else:
317-
raise ValueError("Unrecognized spatial query type. " +
318-
"Must be one of `Cone`, `Box`, `Polygon`, or `All-Sky`.")
260+
raise ValueError("Unrecognized spatial query type. "
261+
"Must be one of `Cone`, `Box`, "
262+
"`Polygon`, or `All-Sky`.")
319263

320264
request_payload['spatial'] = spatial
321265

@@ -382,8 +326,9 @@ def _parse_result(self, response, verbose=False):
382326
except Exception as ex:
383327
self.response = response
384328
self.table_parse_error = ex
385-
raise TableParseError("Failed to parse LCOGT votable! The raw response can be found "
386-
"in self.response, and the error in self.table_parse_error.")
329+
raise TableParseError("Failed to parse LCOGT votable! The raw "
330+
" response can be found in self.response,"
331+
" and the error in self.table_parse_error.")
387332

388333
# Convert to astropy.table.Table instance
389334
table = first_table.to_table()

astroquery/lcogt/tests/test_lcogt.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
'Polygon': 'Polygon.xml'}
2121

2222
OBJ_LIST = ["m31", "00h42m44.330s +41d16m07.50s",
23-
commons.GalacticCoordGenerator(l=121.1743, b=-21.5733, unit=(u.deg, u.deg))]
23+
commons.GalacticCoordGenerator(l=121.1743, b=-21.5733, unit=(u.deg,
24+
u.deg))]
2425

2526

2627
def data_path(filename):
@@ -31,11 +32,11 @@ def data_path(filename):
3132
@pytest.fixture
3233
def patch_get(request):
3334
mp = request.getfuncargvalue("monkeypatch")
34-
mp.setattr(requests, 'get', get_mockreturn)
35+
mp.setattr(lcogt.core.Lcogt, '_request', get_mockreturn)
3536
return mp
3637

3738

38-
def get_mockreturn(url, params=None, timeout=10, **kwargs):
39+
def get_mockreturn(method, url, params=None, timeout=10, **kwargs):
3940
filename = data_path(DATA_FILES[params['spatial']])
4041
content = open(filename, 'rb').read()
4142
return MockResponse(content, **kwargs)

0 commit comments

Comments
 (0)