We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
page_size for /related/ endpoint is set incorrectly and causes 400 error
Currently on the main branch, `/related/` endpoint returns a 400 error. This is caused by incorrectly setting the `page_size` to the number of search results for related. When setting the `page_size`, we also check for the number to be between 0 and 500, and when the number of search results is more than that, the `/related` endpoint returns a 400 error:

https://github.com/WordPress/openverse-api/blob/13673ee8c196c9a6b786a1322d6d65b97c6ca708/openverse_api/catalog/api/views/media_views.py#L97-L108

This is the code that throws the error, in `openverse_api/catalog/api/utils/pagination.py`:
```
 @page_size.setter
    def page_size(self, value):
        logging.info(f'Setting page size to {value}')
        if value is None:
            return
        value = int(value)  # convert str params to int
        if value <= 0 or value > 500:
            raise get_api_exception("Page size must be between 0 & 500.", 400)
        self._page_size = value
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `openverse_api/catalog/api/views/media_views.py`
Content:
```
1 from urllib.error import HTTPError
2 from urllib.request import urlopen
3 
4 from catalog.api.controllers import search_controller
5 from catalog.api.models import ContentProvider
6 from catalog.api.serializers.provider_serializers import ProviderSerializer
7 from catalog.api.utils.exceptions import get_api_exception
8 from catalog.api.utils.pagination import StandardPagination
9 from catalog.custom_auto_schema import CustomAutoSchema
10 from django.conf import settings
11 from django.http.response import HttpResponse
12 from rest_framework import status
13 from rest_framework.decorators import action
14 from rest_framework.response import Response
15 from rest_framework.viewsets import ReadOnlyModelViewSet
16 
17 
18 class MediaViewSet(ReadOnlyModelViewSet):
19     swagger_schema = CustomAutoSchema
20 
21     lookup_field = "identifier"
22     # TODO: https://github.com/encode/django-rest-framework/pull/6789
23     lookup_value_regex = r"[0-9a-f\-]{36}"  # highly simplified approximation
24 
25     pagination_class = StandardPagination
26 
27     # Populate these in the corresponding subclass
28     model_class = None
29     query_serializer_class = None
30     default_index = None
31     qa_index = None
32 
33     def __init__(self, *args, **kwargs):
34         super().__init__(*args, **kwargs)
35         required_fields = [
36             self.model_class,
37             self.query_serializer_class,
38             self.default_index,
39             self.qa_index,
40         ]
41         if any(val is None for val in required_fields):
42             msg = "Viewset fields are not completely populated."
43             raise ValueError(msg)
44 
45     def get_queryset(self):
46         return self.model_class.objects.all()
47 
48     # Standard actions
49 
50     def list(self, request, *_, **__):
51         self.paginator.page_size = request.query_params.get("page_size")
52         page_size = self.paginator.page_size
53         self.paginator.page = request.query_params.get("page")
54         page = self.paginator.page
55 
56         params = self.query_serializer_class(data=request.query_params)
57         params.is_valid(raise_exception=True)
58 
59         hashed_ip = hash(self._get_user_ip(request))
60         qa = params.validated_data["qa"]
61         filter_dead = params.validated_data["filter_dead"]
62 
63         search_index = self.qa_index if qa else self.default_index
64         try:
65             results, num_pages, num_results = search_controller.search(
66                 params,
67                 search_index,
68                 page_size,
69                 hashed_ip,
70                 request,
71                 filter_dead,
72                 page,
73             )
74             self.paginator.page_count = num_pages
75             self.paginator.result_count = num_results
76         except ValueError as e:
77             raise get_api_exception(getattr(e, "message", str(e)))
78 
79         serializer = self.get_serializer(results, many=True)
80         return self.get_paginated_response(serializer.data)
81 
82     # Extra actions
83 
84     @action(detail=False, serializer_class=ProviderSerializer, pagination_class=None)
85     def stats(self, *_, **__):
86         source_counts = search_controller.get_sources(self.default_index)
87         context = self.get_serializer_context() | {
88             "source_counts": source_counts,
89         }
90 
91         providers = ContentProvider.objects.filter(
92             media_type=self.default_index, filter_content=False
93         )
94         serializer = self.get_serializer(providers, many=True, context=context)
95         return Response(serializer.data)
96 
97     @action(detail=True)
98     def related(self, request, identifier=None, *_, **__):
99         try:
100             results, num_results = search_controller.related_media(
101                 uuid=identifier,
102                 index=self.default_index,
103                 request=request,
104                 filter_dead=True,
105             )
106             self.paginator.result_count = num_results
107             self.paginator.page_count = 1
108             self.paginator.page_size = num_results
109         except ValueError as e:
110             raise get_api_exception(getattr(e, "message", str(e)))
111 
112         serializer = self.get_serializer(results, many=True)
113         return self.get_paginated_response(serializer.data)
114 
115     def report(self, request, *_, **__):
116         media = self.get_object()
117         identifier = media.identifier
118         serializer = self.get_serializer(data=request.data)
119         if not serializer.is_valid():
120             raise get_api_exception("Invalid input.", 400)
121         report = serializer.save(identifier=identifier)
122 
123         serializer = self.get_serializer(report)
124         return Response(data=serializer.data, status=status.HTTP_201_CREATED)
125 
126     # Helper functions
127 
128     @staticmethod
129     def _get_user_ip(request):
130         """
131         Read request headers to find the correct IP address.
132         It is assumed that X-Forwarded-For has been sanitized by the load
133         balancer and thus cannot be rewritten by malicious users.
134         :param request: A Django request object.
135         :return: An IP address.
136         """
137         x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
138         if x_forwarded_for:
139             ip = x_forwarded_for.split(",")[0]
140         else:
141             ip = request.META.get("REMOTE_ADDR")
142         return ip
143 
144     @staticmethod
145     def _get_proxied_image(image_url, width=settings.THUMBNAIL_WIDTH_PX):
146         if width is None:  # full size
147             proxy_upstream = f"{settings.THUMBNAIL_PROXY_URL}/{image_url}"
148         else:
149             proxy_upstream = (
150                 f"{settings.THUMBNAIL_PROXY_URL}/"
151                 f"{settings.THUMBNAIL_WIDTH_PX},fit/"
152                 f"{image_url}"
153             )
154         try:
155             upstream_response = urlopen(proxy_upstream)
156             status = upstream_response.status
157             content_type = upstream_response.headers.get("Content-Type")
158         except HTTPError:
159             raise get_api_exception("Failed to render thumbnail.")
160 
161         response = HttpResponse(
162             upstream_response.read(), status=status, content_type=content_type
163         )
164 
165         return response
166
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/openverse_api/catalog/api/views/media_views.py b/openverse_api/catalog/api/views/media_views.py
--- a/openverse_api/catalog/api/views/media_views.py
+++ b/openverse_api/catalog/api/views/media_views.py
@@ -105,7 +105,8 @@
             )
             self.paginator.result_count = num_results
             self.paginator.page_count = 1
-            self.paginator.page_size = num_results
+            # `page_size` refers to the maximum number of related images to return.
+            self.paginator.page_size = 10
         except ValueError as e:
             raise get_api_exception(getattr(e, "message", str(e)))

{"golden_diff": "diff --git a/openverse_api/catalog/api/views/media_views.py b/openverse_api/catalog/api/views/media_views.py\n--- a/openverse_api/catalog/api/views/media_views.py\n+++ b/openverse_api/catalog/api/views/media_views.py\n@@ -105,7 +105,8 @@\n             )\n             self.paginator.result_count = num_results\n             self.paginator.page_count = 1\n-            self.paginator.page_size = num_results\n+            # `page_size` refers to the maximum number of related images to return.\n+            self.paginator.page_size = 10\n         except ValueError as e:\n             raise get_api_exception(getattr(e, \"message\", str(e)))\n", "issue": "page_size for /related/ endpoint is set incorrectly and causes 400 error\nCurrently on the main branch, `/related/` endpoint returns a 400 error. This is caused by incorrectly setting the `page_size` to the number of search results for related. When setting the `page_size`, we also check for the number to be between 0 and 500, and when the number of search results is more than that, the `/related` endpoint returns a 400 error:\r\n\r\nhttps://github.com/WordPress/openverse-api/blob/13673ee8c196c9a6b786a1322d6d65b97c6ca708/openverse_api/catalog/api/views/media_views.py#L97-L108\r\n\r\nThis is the code that throws the error, in `openverse_api/catalog/api/utils/pagination.py`:\r\n```\r\n @page_size.setter\r\n    def page_size(self, value):\r\n        logging.info(f'Setting page size to {value}')\r\n        if value is None:\r\n            return\r\n        value = int(value)  # convert str params to int\r\n        if value <= 0 or value > 500:\r\n            raise get_api_exception(\"Page size must be between 0 & 500.\", 400)\r\n        self._page_size = value\r\n```\n", "before_files": [{"content": "from urllib.error import HTTPError\nfrom urllib.request import urlopen\n\nfrom catalog.api.controllers import search_controller\nfrom catalog.api.models import ContentProvider\nfrom catalog.api.serializers.provider_serializers import ProviderSerializer\nfrom catalog.api.utils.exceptions import get_api_exception\nfrom catalog.api.utils.pagination import StandardPagination\nfrom catalog.custom_auto_schema import CustomAutoSchema\nfrom django.conf import settings\nfrom django.http.response import HttpResponse\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ReadOnlyModelViewSet\n\n\nclass MediaViewSet(ReadOnlyModelViewSet):\n    swagger_schema = CustomAutoSchema\n\n    lookup_field = \"identifier\"\n    # TODO: https://github.com/encode/django-rest-framework/pull/6789\n    lookup_value_regex = r\"[0-9a-f\\-]{36}\"  # highly simplified approximation\n\n    pagination_class = StandardPagination\n\n    # Populate these in the corresponding subclass\n    model_class = None\n    query_serializer_class = None\n    default_index = None\n    qa_index = None\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        required_fields = [\n            self.model_class,\n            self.query_serializer_class,\n            self.default_index,\n            self.qa_index,\n        ]\n        if any(val is None for val in required_fields):\n            msg = \"Viewset fields are not completely populated.\"\n            raise ValueError(msg)\n\n    def get_queryset(self):\n        return self.model_class.objects.all()\n\n    # Standard actions\n\n    def list(self, request, *_, **__):\n        self.paginator.page_size = request.query_params.get(\"page_size\")\n        page_size = self.paginator.page_size\n        self.paginator.page = request.query_params.get(\"page\")\n        page = self.paginator.page\n\n        params = self.query_serializer_class(data=request.query_params)\n        params.is_valid(raise_exception=True)\n\n        hashed_ip = hash(self._get_user_ip(request))\n        qa = params.validated_data[\"qa\"]\n        filter_dead = params.validated_data[\"filter_dead\"]\n\n        search_index = self.qa_index if qa else self.default_index\n        try:\n            results, num_pages, num_results = search_controller.search(\n                params,\n                search_index,\n                page_size,\n                hashed_ip,\n                request,\n                filter_dead,\n                page,\n            )\n            self.paginator.page_count = num_pages\n            self.paginator.result_count = num_results\n        except ValueError as e:\n            raise get_api_exception(getattr(e, \"message\", str(e)))\n\n        serializer = self.get_serializer(results, many=True)\n        return self.get_paginated_response(serializer.data)\n\n    # Extra actions\n\n    @action(detail=False, serializer_class=ProviderSerializer, pagination_class=None)\n    def stats(self, *_, **__):\n        source_counts = search_controller.get_sources(self.default_index)\n        context = self.get_serializer_context() | {\n            \"source_counts\": source_counts,\n        }\n\n        providers = ContentProvider.objects.filter(\n            media_type=self.default_index, filter_content=False\n        )\n        serializer = self.get_serializer(providers, many=True, context=context)\n        return Response(serializer.data)\n\n    @action(detail=True)\n    def related(self, request, identifier=None, *_, **__):\n        try:\n            results, num_results = search_controller.related_media(\n                uuid=identifier,\n                index=self.default_index,\n                request=request,\n                filter_dead=True,\n            )\n            self.paginator.result_count = num_results\n            self.paginator.page_count = 1\n            self.paginator.page_size = num_results\n        except ValueError as e:\n            raise get_api_exception(getattr(e, \"message\", str(e)))\n\n        serializer = self.get_serializer(results, many=True)\n        return self.get_paginated_response(serializer.data)\n\n    def report(self, request, *_, **__):\n        media = self.get_object()\n        identifier = media.identifier\n        serializer = self.get_serializer(data=request.data)\n        if not serializer.is_valid():\n            raise get_api_exception(\"Invalid input.\", 400)\n        report = serializer.save(identifier=identifier)\n\n        serializer = self.get_serializer(report)\n        return Response(data=serializer.data, status=status.HTTP_201_CREATED)\n\n    # Helper functions\n\n    @staticmethod\n    def _get_user_ip(request):\n        \"\"\"\n        Read request headers to find the correct IP address.\n        It is assumed that X-Forwarded-For has been sanitized by the load\n        balancer and thus cannot be rewritten by malicious users.\n        :param request: A Django request object.\n        :return: An IP address.\n        \"\"\"\n        x_forwarded_for = request.META.get(\"HTTP_X_FORWARDED_FOR\")\n        if x_forwarded_for:\n            ip = x_forwarded_for.split(\",\")[0]\n        else:\n            ip = request.META.get(\"REMOTE_ADDR\")\n        return ip\n\n    @staticmethod\n    def _get_proxied_image(image_url, width=settings.THUMBNAIL_WIDTH_PX):\n        if width is None:  # full size\n            proxy_upstream = f\"{settings.THUMBNAIL_PROXY_URL}/{image_url}\"\n        else:\n            proxy_upstream = (\n                f\"{settings.THUMBNAIL_PROXY_URL}/\"\n                f\"{settings.THUMBNAIL_WIDTH_PX},fit/\"\n                f\"{image_url}\"\n            )\n        try:\n            upstream_response = urlopen(proxy_upstream)\n            status = upstream_response.status\n            content_type = upstream_response.headers.get(\"Content-Type\")\n        except HTTPError:\n            raise get_api_exception(\"Failed to render thumbnail.\")\n\n        response = HttpResponse(\n            upstream_response.read(), status=status, content_type=content_type\n        )\n\n        return response\n", "path": "openverse_api/catalog/api/views/media_views.py"}], "after_files": [{"content": "from urllib.error import HTTPError\nfrom urllib.request import urlopen\n\nfrom catalog.api.controllers import search_controller\nfrom catalog.api.models import ContentProvider\nfrom catalog.api.serializers.provider_serializers import ProviderSerializer\nfrom catalog.api.utils.exceptions import get_api_exception\nfrom catalog.api.utils.pagination import StandardPagination\nfrom catalog.custom_auto_schema import CustomAutoSchema\nfrom django.conf import settings\nfrom django.http.response import HttpResponse\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ReadOnlyModelViewSet\n\n\nclass MediaViewSet(ReadOnlyModelViewSet):\n    swagger_schema = CustomAutoSchema\n\n    lookup_field = \"identifier\"\n    # TODO: https://github.com/encode/django-rest-framework/pull/6789\n    lookup_value_regex = r\"[0-9a-f\\-]{36}\"  # highly simplified approximation\n\n    pagination_class = StandardPagination\n\n    # Populate these in the corresponding subclass\n    model_class = None\n    query_serializer_class = None\n    default_index = None\n    qa_index = None\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        required_fields = [\n            self.model_class,\n            self.query_serializer_class,\n            self.default_index,\n            self.qa_index,\n        ]\n        if any(val is None for val in required_fields):\n            msg = \"Viewset fields are not completely populated.\"\n            raise ValueError(msg)\n\n    def get_queryset(self):\n        return self.model_class.objects.all()\n\n    # Standard actions\n\n    def list(self, request, *_, **__):\n        self.paginator.page_size = request.query_params.get(\"page_size\")\n        page_size = self.paginator.page_size\n        self.paginator.page = request.query_params.get(\"page\")\n        page = self.paginator.page\n\n        params = self.query_serializer_class(data=request.query_params)\n        params.is_valid(raise_exception=True)\n\n        hashed_ip = hash(self._get_user_ip(request))\n        qa = params.validated_data[\"qa\"]\n        filter_dead = params.validated_data[\"filter_dead\"]\n\n        search_index = self.qa_index if qa else self.default_index\n        try:\n            results, num_pages, num_results = search_controller.search(\n                params,\n                search_index,\n                page_size,\n                hashed_ip,\n                request,\n                filter_dead,\n                page,\n            )\n            self.paginator.page_count = num_pages\n            self.paginator.result_count = num_results\n        except ValueError as e:\n            raise get_api_exception(getattr(e, \"message\", str(e)))\n\n        serializer = self.get_serializer(results, many=True)\n        return self.get_paginated_response(serializer.data)\n\n    # Extra actions\n\n    @action(detail=False, serializer_class=ProviderSerializer, pagination_class=None)\n    def stats(self, *_, **__):\n        source_counts = search_controller.get_sources(self.default_index)\n        context = self.get_serializer_context() | {\n            \"source_counts\": source_counts,\n        }\n\n        providers = ContentProvider.objects.filter(\n            media_type=self.default_index, filter_content=False\n        )\n        serializer = self.get_serializer(providers, many=True, context=context)\n        return Response(serializer.data)\n\n    @action(detail=True)\n    def related(self, request, identifier=None, *_, **__):\n        try:\n            results, num_results = search_controller.related_media(\n                uuid=identifier,\n                index=self.default_index,\n                request=request,\n                filter_dead=True,\n            )\n            self.paginator.result_count = num_results\n            self.paginator.page_count = 1\n            # `page_size` refers to the maximum number of related images to return.\n            self.paginator.page_size = 10\n        except ValueError as e:\n            raise get_api_exception(getattr(e, \"message\", str(e)))\n\n        serializer = self.get_serializer(results, many=True)\n        return self.get_paginated_response(serializer.data)\n\n    def report(self, request, *_, **__):\n        media = self.get_object()\n        identifier = media.identifier\n        serializer = self.get_serializer(data=request.data)\n        if not serializer.is_valid():\n            raise get_api_exception(\"Invalid input.\", 400)\n        report = serializer.save(identifier=identifier)\n\n        serializer = self.get_serializer(report)\n        return Response(data=serializer.data, status=status.HTTP_201_CREATED)\n\n    # Helper functions\n\n    @staticmethod\n    def _get_user_ip(request):\n        \"\"\"\n        Read request headers to find the correct IP address.\n        It is assumed that X-Forwarded-For has been sanitized by the load\n        balancer and thus cannot be rewritten by malicious users.\n        :param request: A Django request object.\n        :return: An IP address.\n        \"\"\"\n        x_forwarded_for = request.META.get(\"HTTP_X_FORWARDED_FOR\")\n        if x_forwarded_for:\n            ip = x_forwarded_for.split(\",\")[0]\n        else:\n            ip = request.META.get(\"REMOTE_ADDR\")\n        return ip\n\n    @staticmethod\n    def _get_proxied_image(image_url, width=settings.THUMBNAIL_WIDTH_PX):\n        if width is None:  # full size\n            proxy_upstream = f\"{settings.THUMBNAIL_PROXY_URL}/{image_url}\"\n        else:\n            proxy_upstream = (\n                f\"{settings.THUMBNAIL_PROXY_URL}/\"\n                f\"{settings.THUMBNAIL_WIDTH_PX},fit/\"\n                f\"{image_url}\"\n            )\n        try:\n            upstream_response = urlopen(proxy_upstream)\n            status = upstream_response.status\n            content_type = upstream_response.headers.get(\"Content-Type\")\n        except HTTPError:\n            raise get_api_exception(\"Failed to render thumbnail.\")\n\n        response = HttpResponse(\n            upstream_response.read(), status=status, content_type=content_type\n        )\n\n        return response\n", "path": "openverse_api/catalog/api/views/media_views.py"}]}