Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Raise `UpstreamThumbnailException` for unsuccessful requests (#1892)

Krystle Salazar11926a78cfe8
diff --git a/api/catalog/api/utils/photon.py b/api/catalog/api/utils/photon.py
index 78d85d5bf..14e130d68 100644
--- a/api/catalog/api/utils/photon.py
+++ b/api/catalog/api/utils/photon.py
@@ -27,15 +27,11 @@ HEADERS = {
}
-def get(
- image_url: str,
- accept_header: str = "image/*",
- is_full_size: bool = False,
- is_compressed: bool = True,
-) -> HttpResponse:
- logger = parent_logger.getChild("get")
- # Photon options documented here:
- # https://developer.wordpress.com/docs/photon/api/
+def _get_photon_params(image_url, is_full_size, is_compressed):
+ """
+ Photon options documented here:
+ https://developer.wordpress.com/docs/photon/api/
+ """
params = {}
if not is_full_size:
@@ -58,35 +54,38 @@ def get(
# do not serve over HTTP and do not have a redirect)
params["ssl"] = "true"
- # Photon excludes the protocol so we need to reconstruct the url + port + path
+ return params, parsed_image_url
+
+
+def get(
+ image_url: str,
+ accept_header: str = "image/*",
+ is_full_size: bool = False,
+ is_compressed: bool = True,
+) -> HttpResponse:
+ logger = parent_logger.getChild("get")
+ params, parsed_image_url = _get_photon_params(
+ image_url, is_full_size, is_compressed
+ )
+
+ # Photon excludes the protocol, so we need to reconstruct the url + port + path
# to send as the "path" of the Photon request
domain = parsed_image_url.netloc
path = parsed_image_url.path
upstream_url = f"{settings.PHOTON_ENDPOINT}{domain}{path}"
- try:
- headers = {"Accept": accept_header} | HEADERS
- if settings.PHOTON_AUTH_KEY:
- headers["X-Photon-Authentication"] = settings.PHOTON_AUTH_KEY
+ headers = {"Accept": accept_header} | HEADERS
+ if settings.PHOTON_AUTH_KEY:
+ headers["X-Photon-Authentication"] = settings.PHOTON_AUTH_KEY
+ try:
upstream_response = requests.get(
upstream_url,
timeout=15,
params=params,
headers=headers,
)
- res_status = upstream_response.status_code
- content_type = upstream_response.headers.get("Content-Type")
- logger.debug(
- "Image proxy response "
- f"status: {res_status}, content-type: {content_type}"
- )
-
- return HttpResponse(
- upstream_response.content,
- status=res_status,
- content_type=content_type,
- )
+ upstream_response.raise_for_status()
except requests.ReadTimeout as exc:
# Count the incident so that we can identify providers with most timeouts.
key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}{domain}"
@@ -102,9 +101,22 @@ def get(
)
except requests.RequestException as exc:
sentry_sdk.capture_exception(exc)
- raise UpstreamThumbnailException(f"Failed to render thumbnail: {exc}")
+ raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")
except Exception as exc:
sentry_sdk.capture_exception(exc)
raise UpstreamThumbnailException(
- f"Failed to render thumbnail due to unidentified exception: {exc}"
+ f"Failed to render thumbnail due to unidentified exception. {exc}"
+ )
+ else:
+ res_status = upstream_response.status_code
+ content_type = upstream_response.headers.get("Content-Type")
+ logger.debug(
+ "Image proxy response "
+ f"status: {res_status}, content-type: {content_type}"
+ )
+
+ return HttpResponse(
+ upstream_response.content,
+ status=res_status,
+ content_type=content_type,
)
diff --git a/api/test/unit/utils/photon_test.py b/api/test/unit/utils/photon_test.py
index 5ca0582fd..560acf0a6 100644
--- a/api/test/unit/utils/photon_test.py
+++ b/api/test/unit/utils/photon_test.py
@@ -239,28 +239,25 @@ def test_get_timeout_existing_cache_key(
assert redis.get(key) == b"6"
-def test_get_request_exception(capture_exception, setup_requests_get_exception):
- exc = requests.RequestException()
- setup_requests_get_exception(exc)
+ "exception, expected_message",
+ [
+ ( # Includes HTTP response errors
+ requests.RequestException(),
+ r"Failed to render thumbnail.",
+ ),
+ (ValueError(), r"due to unidentified exception."),
+ ],
+)
+def test_get_raise_exception_msg(
+ capture_exception, setup_requests_get_exception, exception, expected_message
+):
+ setup_requests_get_exception(exception)
- with pytest.raises(
- UpstreamThumbnailException, match=r"Failed to render thumbnail:"
- ):
+ with pytest.raises(UpstreamThumbnailException, match=expected_message):
photon_get(TEST_IMAGE_URL)
- capture_exception.assert_called_once_with(exc)
-
-
-def test_get_generic_exception(capture_exception, setup_requests_get_exception):
- exc = ValueError()
- setup_requests_get_exception(exc)
-
- with pytest.raises(
- UpstreamThumbnailException, match=r"due to unidentified exception"
- ):
- photon_get(TEST_IMAGE_URL)
-
- capture_exception.assert_called_once_with(exc)
+ capture_exception.assert_called_once_with(exception)
@pook.on
@@ -287,3 +284,15 @@ def test_get_successful_https_image_url_sends_ssl_parameter(mock_image_data):
assert res.content == MOCK_BODY.encode()
assert res.status_code == 200
assert mock_get.matched
+
+
+def test_get_unsuccessful_request_raises_exception():
+ mock_get: pook.Mock = pook.get(PHOTON_URL_FOR_TEST_IMAGE).reply(404).mock
+
+ with pytest.raises(
+ UpstreamThumbnailException, match=r"Failed to render thumbnail."
+ ):
+ photon_get(TEST_IMAGE_URL)
+
+ assert mock_get.matched