DRF
는 기존 장고의 View
클래스를 상속하는 APIView
를 제공한다.view
클래스와 다른점은 다음과 같다.HttpRequest
가 아닌DRF
의 Request
클래스를 통해 핸들러 메서드에 전달된다.DRF
의 Response
객체를 반환한다. 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
를 볼 수 있다.