Skip to content

Commit

Permalink
Merge pull request #2583 from AlinderS/remove-deprecated-code
Browse files Browse the repository at this point in the history
Remove deprecated function `send_request()`
  • Loading branch information
bsipocz authored Nov 16, 2022
2 parents 0eb8daa + 855d19b commit b1805f6
Show file tree
Hide file tree
Showing 5 changed files with 5 additions and 139 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ Infrastructure, Utility and Other Changes and Additions
- Removal of the non-functional ``noirlab`` module because the current module
is incompatible with the new upstream API. [#2579]

- Removed deprecated function ``utils.commons.send_request()``. [#2583]


0.4.6 (2022-03-22)
==================
Expand Down
3 changes: 1 addition & 2 deletions astroquery/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .progressbar import chunk_report, chunk_read
from .download_file_list import download_list_of_fitsfiles
from .class_or_instance import class_or_instance
from .commons import (send_request, parse_coordinates, TableList, suppress_vo_warnings,
from .commons import (parse_coordinates, TableList, suppress_vo_warnings,
validate_email, ASTROPY_LT_4_1, ASTROPY_LT_4_3, ASTROPY_LT_5_0,
ASTROPY_LT_5_1)
from .process_asyncs import async_to_sync
Expand All @@ -17,7 +17,6 @@
__all__ = ['chunk_report', 'chunk_read',
'download_list_of_fitsfiles',
'class_or_instance',
'send_request',
'parse_coordinates',
'TableList',
'suppress_vo_warnings',
Expand Down
64 changes: 2 additions & 62 deletions astroquery/utils/commons.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,21 @@
from io import BytesIO, StringIO
from urllib.error import URLError

import requests

import astropy.units as u
from collections import OrderedDict
from astropy.utils import deprecated, minversion
from astropy.utils import minversion
import astropy.utils.data as aud
from astropy.io import fits, votable

from astropy.coordinates import Angle, BaseCoordinateFrame, SkyCoord

from ..exceptions import TimeoutError, InputWarning
from .. import version


CoordClasses = (SkyCoord, BaseCoordinateFrame)


__all__ = ['send_request',
'parse_coordinates',
__all__ = ['parse_coordinates',
'TableList',
'suppress_vo_warnings',
'validate_email',
Expand All @@ -47,62 +43,6 @@
# ASTROPY_LT_5_1 = not minversion('astropy', '5.1')


@deprecated('0.4.4', alternative='astroquery.query.BaseQuery._request')
def send_request(url, data, timeout, request_type='POST', headers={},
**kwargs):
"""
A utility function that post HTTP requests to remote server
and returns the HTTP response.
Parameters
----------
url : str
The URL of the remote server
data : dict
A dictionary representing the payload to be posted via the HTTP request
timeout : int, quantity_like
Time limit for establishing successful connection with remote server
request_type : str
options are 'POST' (default) and 'GET'. Determines whether to perform
an HTTP POST or an HTTP GET request
headers : dict
POST or GET headers. user-agent will be set to
astropy:astroquery.version
Returns
-------
response : `requests.Response`
Response object returned by the remote server
"""
headers['User-Agent'] = ('astropy:astroquery.{vers}'
.format(vers=version.version))

if hasattr(timeout, "unit"):
warnings.warn("Converting timeout to seconds and truncating "
"to integer.", InputWarning)
timeout = int(timeout.to(u.s).value)

try:
if request_type == 'GET':
response = requests.get(url, params=data, timeout=timeout,
headers=headers, **kwargs)
elif request_type == 'POST':
response = requests.post(url, data=data, timeout=timeout,
headers=headers, **kwargs)
else:
raise ValueError("request_type must be either 'GET' or 'POST'.")

response.raise_for_status()

return response

except requests.exceptions.Timeout:
raise TimeoutError("Query timed out, time elapsed {time}s".
format(time=timeout))
except requests.exceptions.RequestException as ex:
raise Exception("Query failed: {0}\n".format(ex))


def radius_to_unit(radius, unit='degree'):
"""
Helper function: Parse a radius, then return its value in degrees
Expand Down
64 changes: 0 additions & 64 deletions astroquery/utils/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from collections import OrderedDict
import os
import requests
import pytest
import tempfile
import textwrap
Expand All @@ -14,7 +13,6 @@
import astropy.units as u
from astropy.table import Table
import astropy.utils.data as aud
from astropy.utils.exceptions import AstropyDeprecationWarning

from ...utils import chunk_read, chunk_report, class_or_instance, commons
from ...utils.process_asyncs import async_to_sync_docstr, async_to_sync
Expand Down Expand Up @@ -79,68 +77,6 @@ def test_parse_coordinates_4():
assert c.to_string() == coordinates


def test_send_request_post(monkeypatch):
def mock_post(url, data, timeout, headers={}, status_code=200):
class SpecialMockResponse:

def __init__(self, url, data, headers, status_code):
self.url = url
self.data = data
self.headers = headers
self.status_code = status_code

def raise_for_status(self):
pass

return SpecialMockResponse(url, data, headers=headers,
status_code=status_code)
monkeypatch.setattr(requests, 'post', mock_post)

with pytest.warns(AstropyDeprecationWarning):
response = commons.send_request('https://github.com/astropy/astroquery',
data=dict(msg='ok'), timeout=30)
assert response.url == 'https://github.com/astropy/astroquery'
assert response.data == dict(msg='ok')
assert 'astroquery' in response.headers['User-Agent']
assert response.headers['User-Agent'].endswith("_testrun")


def test_send_request_get(monkeypatch):
def mock_get(url, params, timeout, headers={}, status_code=200):
req = requests.Request(
'GET', url, params=params, headers=headers).prepare()
req.status_code = status_code
req.raise_for_status = lambda: None
return req
monkeypatch.setattr(requests, 'get', mock_get)
with pytest.warns(AstropyDeprecationWarning):
response = commons.send_request('https://github.com/astropy/astroquery',
dict(a='b'), 60, request_type='GET')
assert response.url == 'https://github.com/astropy/astroquery?a=b'


def test_quantity_timeout(monkeypatch):
def mock_get(url, params, timeout, headers={}, status_code=200):
req = requests.Request(
'GET', url, params=params, headers=headers).prepare()
req.status_code = status_code
req.raise_for_status = lambda: None
return req
monkeypatch.setattr(requests, 'get', mock_get)
with pytest.warns(AstropyDeprecationWarning):
response = commons.send_request('https://github.com/astropy/astroquery',
dict(a='b'), 1 * u.min,
request_type='GET')
assert response.url == 'https://github.com/astropy/astroquery?a=b'


def test_send_request_err():
with pytest.raises(ValueError):
with pytest.warns(AstropyDeprecationWarning):
commons.send_request('https://github.com/astropy/astroquery',
dict(a='b'), 60, request_type='PUT')


col_1 = [1, 2, 3]
col_2 = [0, 1, 0, 1, 0, 1]
col_3 = ['v', 'w', 'x', 'y', 'z']
Expand Down
11 changes: 0 additions & 11 deletions astroquery/xmatch/tests/test_xmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from astropy.table import Table
from astropy.units import arcsec

from ...utils import commons
from astroquery.utils.mocks import MockResponse
from ...xmatch import XMatch

Expand Down Expand Up @@ -75,11 +74,6 @@ def test_xmatch_is_avail_table(monkeypatch):
def test_xmatch_query_local(monkeypatch):
xm = XMatch()
monkeypatch.setattr(xm, '_request', request_mockreturn)
monkeypatch.setattr(
commons,
'send_request',
lambda url, data, timeout, request_type='POST', headers={}, **kwargs:
request_mockreturn(request_type, url, data, **kwargs))
with open(DATA_DIR / "posList.csv") as pos_list:
response = xm.query_async(
cat1=pos_list, cat2='vizier:II/246/out', max_distance=5 * arcsec,
Expand All @@ -96,11 +90,6 @@ def test_xmatch_query_local(monkeypatch):
def test_xmatch_query_cat1_table_local(monkeypatch):
xm = XMatch()
monkeypatch.setattr(xm, '_request', request_mockreturn)
monkeypatch.setattr(
commons,
'send_request',
lambda url, data, timeout, request_type='POST', headers={}, **kwargs:
request_mockreturn(request_type, url, data, **kwargs))
with open(DATA_DIR / "posList.csv") as pos_list:
input_table = Table.read(pos_list.readlines(),
format='ascii.csv',
Expand Down

0 comments on commit b1805f6

Please sign in to comment.