Class-based Views


Django's class-based views are a welcome departure from old-style views 장고의 클래스 기반 뷰는 기존에 있던 구식의 뷰에서 환영받는 새 출발이다.

REST Framework는 장고의 View 클래스를 하위 클래스로 취하는 APIView 클래스를 제공한다.

APIView 클래스는 기존의 View 클래스로부터 아래의 다른점들을 가진다:

APIView를 사용한다는건 기존의 View 클래스를 사용하는 것과 매우 비슷하다. 예를 들면, 기존과 같이 들어오는 요청은 .get()이나 .post() 같은 적절한 핸들러 메소드에 배치된다. 추가적으로 API 규정의 여러 측면을 제어하는 여러 속성들을 클래스에 설정할 수 있다.

예를 들면:

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)

API Policy Attributes

다음의 속성들은 API 뷰의 pluggable aspects를 제어한다.