/
zru
/
drevix
Обзор
Документация
Войти
/
zru
/
drevix
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
back/comments/api/views.py
72 строки
3 KB
zru
Доступ открыт
08 июн 2026, 20:37
Верифицирован
08 июн 2026, 20:37
daaa836
Код
Авторство
О чём код?
from django.http import Http404 from rest_framework import status from rest_framework.exceptions import PermissionDenied, ValidationError from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from comments.api.serializers import CommentSerializer, CreateCommentSerializer from comments.exceptions import CommentPermissionDenied, CommentValidationError from comments.models import Comment from comments.services import CommentService from nsa.models import NsaEntity class CommentPagination(PageNumberPagination): page_size = 20 page_size_query_param = 'page_size' max_page_size = 100 class EntityCommentListCreateAPIView(APIView): pagination_class = CommentPagination def get_permissions(self): if self.request.method == 'POST': return [IsAuthenticated()] return [AllowAny()] def get(self, request, entity_id: int): try: comments = CommentService().list_for_entity(entity_id=entity_id) except NsaEntity.DoesNotExist as exc: raise Http404 from exc paginator = self.pagination_class() page = paginator.paginate_queryset(comments, request, view=self) serializer = CommentSerializer(page, many=True) return paginator.get_paginated_response(serializer.data) def post(self, request, entity_id: int): serializer = CreateCommentSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: comment = CommentService().add_comment( author=request.user, entity_id=entity_id, **serializer.validated_data, ) except NsaEntity.DoesNotExist as exc: raise Http404 from exc except Comment.DoesNotExist as exc: raise ValidationError({'answer_id': 'Answer comment not found.'}) from exc except CommentValidationError as exc: raise ValidationError(str(exc)) from exc return Response(CommentSerializer(comment).data, status=status.HTTP_201_CREATED) class CommentDetailAPIView(APIView): permission_classes = (IsAuthenticated,) def delete(self, request, comment_id: int): try: CommentService().delete_comment(user=request.user, comment_id=comment_id) except CommentPermissionDenied as exc: raise PermissionDenied('Only comment author or administrator can delete comment.') from exc except Comment.DoesNotExist as exc: raise Http404 from exc return Response(status=status.HTTP_204_NO_CONTENT)