3-1. Views

SINHOLEE·2020년 8월 27일
0

Class-based Views

  • DRF는 기존 장고의 View클래스를 상속하는 APIView를 제공한다.
  • 기존의 view클래스와 다른점은 다음과 같다.
    • 장고의 HttpRequest가 아닌DRFRequest클래스를 통해 핸들러 메서드에 전달된다.
    • 핸들러 메서드DRFResponse 객체를 반환한다.
    • view는 1) content negotiation를 다루고 2) 정확한 랜더러를 설정(set)하는 것을 다룬다.(이 부분 이해 안감)
    • 모든 APIException은 적당한 response로 대응할 것이다.
    • request는 핸들러 메서드로 거기 전에 인증, 허가 체크 등이 수행된다.
  • APIView는 기존 장고의 View와 같이 .get(), .post()등 메소드를 사용하면 된다. 뿐만 아니라 다양한 어트리뷰트가 설정되어 있으므로 적당히 사용하면 될 것이다.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User

class ListUsers(APIView):
    """
    View to list all users in the system.

    * Requires token authentication.
    * Only admin users are able to access this view.
    """
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.IsAdminUser]

    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames)

중요: 전체 메소드와 어트리뷰트를 처음 접한다면 APIView, GenericAPIView, 여러개의 Mixin, Viewset을 처음부터 이해하기에는 쉽지 않다. 추가적인 문서가 여기( Classy Django REST Framework) 에 소스코드와 각각의 DRF class-based views 를 볼 수 있다.

profile
엔지니어로 거듭나기

0개의 댓글