Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Convert oembed to async (#3458)
sarayourfriend46ed1a18e1d0
diff --git a/api/api/serializers/image_serializers.py b/api/api/serializers/image_serializers.pyindex 27dd63df9..faf08d7b5 100644--- a/api/api/serializers/image_serializers.py+++ b/api/api/serializers/image_serializers.py@@ -1,7 +1,6 @@from typing import Literalfrom uuid import UUID-from django.core.exceptions import ValidationErrorfrom rest_framework import serializersfrom api.constants.field_order import field_position_map@@ -139,14 +138,7 @@ class OembedRequestSerializer(serializers.Serializer):{"Could not parse identifier from URL.": data["url"]})- try:- image = Image.objects.get(identifier=uuid)- except (Image.DoesNotExist, ValidationError):- raise serializers.ValidationError(- {"Could not find image from the provided URL": data["url"]}- )-- data["image"] = image+ data["identifier"] = uuidreturn datadiff --git a/api/api/utils/asyncio.py b/api/api/utils/asyncio.pyindex 3b41a1f14..cfe3d4c1e 100644--- a/api/api/utils/asyncio.py+++ b/api/api/utils/asyncio.py@@ -2,6 +2,10 @@ import asyncioimport loggingfrom collections.abc import Awaitable+from rest_framework.generics import get_object_or_404++from asgiref.sync import sync_to_async+parent_logger = logging.getLogger(__name__)@@ -27,3 +31,6 @@ def do_not_wait_for(awaitable: Awaitable) -> None:raise excloop.create_task(awaitable)+++aget_object_or_404 = sync_to_async(get_object_or_404)diff --git a/api/api/views/image_views.py b/api/api/views/image_views.pyindex 597fd84ea..1d07c4351 100644--- a/api/api/views/image_views.py+++ b/api/api/views/image_views.py@@ -6,7 +6,6 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import NotFoundfrom rest_framework.response import Response-import requestsfrom drf_spectacular.utils import extend_schema, extend_schema_viewfrom PIL import Image as PILImage@@ -35,6 +34,8 @@ from api.serializers.image_serializers import ()from api.serializers.media_serializers import PaginatedRequestSerializerfrom api.utils import image_proxy+from api.utils.aiohttp import get_aiohttp_session+from api.utils.asyncio import aget_object_or_404from api.utils.watermark import watermarkfrom api.views.media_views import MediaViewSet@@ -99,7 +100,7 @@ class ImageViewSet(MediaViewSet):url_name="oembed",serializer_class=OembedSerializer,)- def oembed(self, request, *_, **__):+ async def oembed(self, request, *_, **__):"""Retrieve the structured data for a specified image URL as per the[oEmbed spec](https://oembed.com/).@@ -110,12 +111,16 @@ class ImageViewSet(MediaViewSet):params = OembedRequestSerializer(data=request.query_params)params.is_valid(raise_exception=True)- image = params.validated_data["image"]+ identifier = params.validated_data["identifier"]context = self.get_serializer_context()+ image = await aget_object_or_404(Image, identifier=identifier)+if not (image.height and image.width):- image_file = requests.get(image.url, headers=self.OEMBED_HEADERS)- width, height = PILImage.open(io.BytesIO(image_file.content)).size+ session = await get_aiohttp_session()+ image_file = await session.get(image.url, headers=self.OEMBED_HEADERS)+ image_content = await image_file.content.read()+ width, height = PILImage.open(io.BytesIO(image_content)).sizecontext |= {"width": width,"height": height,diff --git a/api/test/test_image_integration.py b/api/test/test_image_integration.pyindex 423db2534..3e2df768b 100644--- a/api/test/test_image_integration.py+++ b/api/test/test_image_integration.py@@ -88,10 +88,26 @@ def test_audio_report(image_fixture):@pytest.mark.parametrize("url, expected_status_code",[- (f"https://any.domain/any/path/{identifier}", 200), # no trailing slash- (f"https://any.domain/any/path/{identifier}/", 200), # trailing slash- ("https://any.domain/any/path/00000000-0000-0000-0000-000000000000", 400),- ("https://any.domain/any/path/not-a-valid-uuid", 400),+ pytest.param(+ f"https://any.domain/any/path/{identifier}",+ 200,+ id="OK; no trailing slash",+ ),+ pytest.param(+ f"https://any.domain/any/path/{identifier}/",+ 200,+ id="OK; with trailing slash",+ ), # trailing slash+ pytest.param(+ "https://any.domain/any/path/00000000-0000-0000-0000-000000000000",+ 404,+ id="Valid UUID but no matching identifier",+ ),+ pytest.param(+ "https://any.domain/any/path/not-a-valid-uuid",+ 400,+ id="not a valid UUID",+ ),],)def test_oembed_endpoint(url, expected_status_code):diff --git a/api/test/unit/views/test_image_views.py b/api/test/unit/views/test_image_views.pyindex 3b919809c..6aef99505 100644--- a/api/test/unit/views/test_image_views.py+++ b/api/test/unit/views/test_image_views.py@@ -1,15 +1,12 @@import json-from collections.abc import Callable-from dataclasses import dataclassfrom pathlib import Path-from test.constants import API_URLfrom test.factory.models.image import ImageFactoryfrom unittest.mock import patchimport pookimport pytestfrom PIL import UnidentifiedImageError-from requests import Request, Response+from requests import Responsefrom api.views.image_views import ImageViewSet@@ -19,48 +16,22 @@ _MOCK_IMAGE_BYTES = (_MOCK_IMAGE_PATH / "sample-image.jpg").read_bytes()_MOCK_IMAGE_INFO = json.loads((_MOCK_IMAGE_PATH / "sample-image-info.json").read_text())-@dataclass-class RequestsFixture:- requests: list[Request]- response_factory: Callable[ # noqa: E731- [Request], Response- ] = lambda x: RequestsFixture._default_response_factory(x)-- @staticmethod- def _default_response_factory(req: Request) -> Response:- res = Response()- res.url = req.url- res.status_code = 200- res._content = _MOCK_IMAGE_BYTES- return res---def requests(monkeypatch) -> RequestsFixture:- fixture = RequestsFixture([])-- def requests_get(url, **kwargs):- req = Request(method="GET", url=url, **kwargs)- fixture.requests.append(req)- response = fixture.response_factory(req)- return response-- monkeypatch.setattr("requests.get", requests_get)-- return fixture--@pytest.mark.django_db-def test_oembed_sends_ua_header(api_client, requests):+def test_oembed_sends_ua_header(api_client):image = ImageFactory.create()image.url = f"https://any.domain/any/path/{image.identifier}"- res = api_client.get(f"{API_URL}/v1/images/oembed/", data={"url": image.url})+ image.save()- assert res.status_code == 200+ with pook.use():+ (+ pook.get(image.url)+ .header("User-Agent", ImageViewSet.OEMBED_HEADERS["User-Agent"])+ .reply(200)+ .body(_MOCK_IMAGE_BYTES, binary=True)+ )+ res = api_client.get("/v1/images/oembed/", data={"url": image.url})- assert len(requests.requests) > 0- for r in requests.requests:- assert r.headers == ImageViewSet.OEMBED_HEADERS+ assert res.status_code == 200@pytest.mark.django_db