코드로 우주평화

Class-based Views 본문

나는 이렇게 본다/Django REST framework

Class-based Views

daco2020 2022. 2. 10. 17:06

 

Class-based Views

클래스 기반 뷰
Django's class-based views are a welcome departure from the old-style views.
장고의 클래스 기반 뷰가 기존 뷰 스타일로 부터 분리된 것은 반가운 일이다.

 

REST framework provides an APIView class, which subclasses Django's View class.

레스트 프레임워크는 장고의 뷰 클래스를 하위 클래스로 분류하는 APIView 클래스를 제공한다.

 

APIView classes are different from regular View classes in the following ways:

APIView 클래스들은 일반적인 뷰 클래스들과 다음과 같은 차이점이 있다.

 

  • Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.
    핸들러 메소드에 전달된 요청은 Django의 HttpRequest 인스턴스가 아니라 REST 프레임워크의 요청 인스턴스가 됩니다.
  • Handler methods may return REST framework's Response, instead of Django's HttpResponse. The view will manage content negotiation and setting the correct renderer on the response.
    핸들러 메소드는 http리스폰이 아닌 레스트 프레임워크의 리스폰으로 반환한다.
    뷰는 콘텐츠 협상과 랜더러의 올바른 응답 설정을 관리할 것이다.
  • Any APIException exceptions will be caught and mediated into appropriate responses.
    모든 API익센셥 예외는 적절한 응답 조정하여 잡아낼 것이다.
  • Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
    들어온 요청들은 핸들러 메서드로 전달하기 전에 인증과 적절한 허가 그리고 또는 쓰로틀 체크를 할 것이다.
  •  

Using the APIView class is pretty much the same as using a regular View class,

API뷰 클래스를 사용하면 기존 뷰 클래스와 상당히 유사할 것이다.

as usual,

평소와 같이

the incoming request is dispatched to an appropriate handler method such as .get() or .post().

들어온 리퀘스트는 적절한 핸들러 메서드인 겟() 또는 포스트() 로 전달된다.

Additionally, a number of attributes may be set on the class that control various aspects of the API policy.

게다가 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)

 

Note: The full methods, attributes on, and relations between Django REST Framework's APIViewGenericAPIView, various Mixins, and Viewsets can be initially complex.

메모 : 모든 메서드, 속성, 그리고 API뷰, 제너릭뷰, 다양한 믹싱, 뷰셋들은 처음에는 복잡할 수 있다.

In addition to the documentation here, the Classy Django REST Framework resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.

여기 문서 외에서도 클레시 장고 레스트 프레임워크 자원이 DRF의 클래스 기반 뷰들 간의 모든 메서드와 속성들의 레퍼런스 탐색을 제공한다.

 

Dispatch methods

*디스패치는 신속이 전달, 파견하다의 뜻을 가짐

 

The following methods are called directly by the view's .dispatch()method.

다음 메서드들은 뷰의 디스패치() 메서드에서 직접 호출된다.

 

These perform any actions that need to occur before or after calling the handler methods such as .get(), .post()put()patch() and .delete().

이들은 핸들러 메서드를 호출하기 전과 후에 발생하는 모든 행동들을 수행한다.

.initial(self, request, *args, **kwargs)

Performs any actions that need to occur before the handler method gets called.

핸들러 메서드가 호출되기 전에 발생하는 모든 행동들을 수행한다.

 

This method is used to enforce permissions and throttling, and perform content negotiation.

이 메서드는 권한과 제한(조절) 그리고 콘텐츠 협상을 수행하는데 사용된다.

 

You won't typically need to override this method.

당신은 일반적으로 메서드를 덮어쓸(재정의) 필요가 없다.

 

.handle_exception(self, exc)

Any exception thrown by the handler method will be passed to this method, which either returns a Response instance, or re-raises the exception.

핸들러 메서드가 발생시킨 모든 예외는 이 메서드로 전달 될 것이고, 어느쪽이든 응답 인스턴스(경우,사례)와 예외를 다시 발생시킨다.

 

The default implementation handles any subclass of rest_framework.exceptions.APIException, as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response.

기본 구현은 rest_framework.exceptions.APIException의 모든 하위 클래스와 Django의 Http404 및 PermissionDenied 예외를 처리하고 적절한 오류 응답을 반환한다.

 

If you need to customize the error responses your API returns you should subclass this method.

만약 너가 너의 API 에러 응답을 커스텀해야 한다면 이 메서드를 하위클래스로 해야 한다.

.initialize_request(self, request, *args, **kwargs)

Ensures that the request object that is passed to the handler method is an instance of Request, rather than the usual Django HttpRequest.

You won't typically need to override this method.

.finalize_response(self, request, response, *args, **kwargs)

Ensures that any Response object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.

You won't typically need to override this method.

 

 

 

Comment

핸들러 메서드는 get, post 같은 view 내 메서드를 뜻하는 것 같다.

콘텐츠 협상은 동일한 URI에서 리소스의 서로 다른 버전을 서브하기 위해 사용되는 메커니즘으로, 사용자 에이전트가 사용자에게 제일 잘 맞는 것이 무엇인지(예를 들어, 문서의 언어, 이미지 포맷 혹은 컨텐츠 인코딩에 있어 어떤 것이 적절한지)를 명시하는 것을 뜻한다.

 

후반 부분은 중요한 내용이 아닌 것 같아 번역하지 않았다.

DRF를 다루는데 우선적으로 다루어야 하는 토픽 위주로 번역해볼 예정이다.

영어실력이 부족하기 때문에 하루에 일정시간 한 토픽씩 진행할 예정이다.

 

문서를 봐도 금방 잊어버리는데 미리 번역해 둔 것을 블로그에 정리해둔다면 더 효과적으로 찾아볼 수 있을 것이라 기대한다.

공식 문서를 보는 습관을 기르기 위해서라도 매일 조금씩 번역하는 습관을 기르자.

 

 

Reference

 

 

Views - Django REST framework

 

www.django-rest-framework.org

 

Content negotiation - HTTP | MDN

HTTP에서, 컨텐츠 협상이란 동일한 URI에서 리소스의 서로 다른 버전을 서브하기 위해 사용되는 메커니즘으로, 사용자 에이전트가 사용자에게 제일 잘 맞는 것이 무엇인지(예를 들어, 문서의 언어

developer.mozilla.org

'나는 이렇게 본다 > Django REST framework' 카테고리의 다른 글

Generic views - Methods  (0) 2022.02.15
Generic views - Attributes  (0) 2022.02.14
Function Based Views  (0) 2022.02.11