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:
- Requests passed to the handler methods will be REST framework's
Request
instances, not Django'sHttpRequest
instances.핸들러 메소드에 전달된 요청은 Django의 HttpRequest 인스턴스가 아니라 REST 프레임워크의 요청 인스턴스가 됩니다.
- Handler methods may return REST framework's
Response
, instead of Django'sHttpResponse
. 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,
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 APIView
, GenericAPIView
, various Mixins
, and Viewsets
can be initially complex.
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.
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.