Add API for latest posts

This commit is contained in:
Jake Howard 2024-01-28 18:06:17 +00:00
parent ae4ea780b7
commit 7d3605f5e1
Signed by: jake
GPG key ID: 57AFB45680EDD477
5 changed files with 48 additions and 2 deletions

View file

@ -2,5 +2,5 @@ from rest_framework.pagination import PageNumberPagination
class CustomPageNumberPagination(PageNumberPagination): class CustomPageNumberPagination(PageNumberPagination):
page_size = 15 page_size = 10
max_page_size = 40 max_page_size = 25

View file

@ -36,3 +36,14 @@ class LMOTFYSerializer(serializers.ModelSerializer):
return self.context["request"].build_absolute_uri(image_url) return self.context["request"].build_absolute_uri(image_url)
return image_url return image_url
class LatestPostSerializer(serializers.ModelSerializer):
full_url = serializers.SerializerMethodField()
class Meta:
model = BlogPostPage
fields = read_only_fields = ["full_url", "title", "date"]
def get_full_url(self, page: Page) -> str:
return page.get_full_url(request=self.context["request"])

View file

@ -86,3 +86,20 @@ class SchemaTestCase(APISimpleTestCase):
def test_schema(self) -> None: def test_schema(self) -> None:
response = self.client.get(reverse("api:schema")) response = self.client.get(reverse("api:schema"))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
class LatestPostsAPIViewTestCase(APITestCase):
url = reverse("api:latest-posts")
@classmethod
def setUpTestData(cls) -> None:
cls.home_page = HomePage.objects.get()
for i in range(4):
BlogPostPageFactory(parent=cls.home_page, title=f"Post {i}")
def test_accessible(self) -> None:
with self.assertNumQueries(5):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["count"], 4)

View file

@ -10,6 +10,7 @@ api_urlpatterns = [
path("ping/", views.PingAPIView.as_view(), name="ping"), path("ping/", views.PingAPIView.as_view(), name="ping"),
path("page-links/", views.PageLinksAPIView.as_view(), name="page-links"), path("page-links/", views.PageLinksAPIView.as_view(), name="page-links"),
path("lmotfy/", views.LMOTFYAPIView.as_view(), name="lmotfy"), path("lmotfy/", views.LMOTFYAPIView.as_view(), name="lmotfy"),
path("latest-posts/", views.LatestPostsAPIView.as_view(), name="latest-posts"),
] ]
schema_view = get_schema_view( schema_view = get_schema_view(

View file

@ -60,3 +60,20 @@ class SwaggerRedirectView(RedirectView):
return HttpResponseRedirect( return HttpResponseRedirect(
self.SWAGGER_EDITOR_URL + request.build_absolute_uri(reverse("api:schema")) self.SWAGGER_EDITOR_URL + request.build_absolute_uri(reverse("api:schema"))
) )
class LatestPostsAPIView(ListAPIView):
"""
List my latest blog posts
"""
serializer_class = serializers.LatestPostSerializer
pagination_class = CustomPageNumberPagination
def get_queryset(self) -> PageQuerySet:
return (
BlogPostPage.objects.live()
.public()
.only("id", "url_path", "title", "date")
.order_by("-date")
)