DRF

What(정의)와 WHY(왜)를 중심으로 공부하기 — 프레임워크(2)

SoniaComp
4 min readApr 13, 2021

내가 DRF 프로젝트를 할 때, 신경썼던 두 가지는 다음과 같다.

공식 문서의 코드 스타일과 디자인을 따름

  • 공식문서에 포함된 디자인 관련 내용
  • 튜토리얼과 예제를 통해 알 수 있는 프레임워크 디자인

직관적이고 이해하기 쉬운 코드

  • 중복 피하기
  • 클래스 이름과 상속 클래스 이름만 보아도 기능을 알 수 있어야 함
  • 뭐든지 다 할 수 있는 것보다 기능을 제한하는게 가독성이 더 좋음

WHAT

  • Django 안에서 RESTful API 서버를 쉽게 구축할 수 있도록 도와주는 오픈소스 라이브러리 입니다.

WHY

  • Serializer 기능: 모델 인스턴스 → JSON형태, Dictionary 형태 직렬화
  • Serialization: 나중에 재구성할 수 있는 포맷으로 변환하는 과정 [ Byte Stream — Primitive 변수로 변환 ]

파이썬의 데이터 타입

  • 실제 데이터 값을 저장하는 원시타입(Primitive type) [boolean, char, 정수, 실수]
  • 메모리 번지 값을 통해 객체를 참조하는 참조타입(Reference type)

→ 접근속도: 원시 타입은 스택 메모리에 값이 존재하지만, 참조 타입은 스택 메모리에는 참조값만 있고, 실제 값은 힙 메모리에 존재한다.

→ 메모리 양: 원시 타입보다 참조 타입이 사용하는 메모리 양이 압도적으로 높다. 메모리 사용적으로도 원시 타입이 참조 타입보다 효율적으로 사용할 수 있다.

ModelSerializer

  • General Serializer와 차이
  • 다른 모델을 참조하는 필드는 각 관계별로 어떻게 정의
  • Generic View + Mixin
  • Concrete View
  • Concrete View 작성시 override (자주 override하는 메소드)

Django-CORS-Header

A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.

Django-Filter

모델 필드를 기준으로 하는 필터링

HTTP 통신

Request

REST framework’s Request class extends the standard HttpRequest, adding support for REST framework's flexible request parsing and request authentication.

  • Request Parsing
    - data
    - query_params [ GET ]
  • Authentication
    - user
    - auth

Responses

Views

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

  1. Django’s HttpRequest → REST framework’s APIView Class
  2. Django’s HttpResponse → REST framework’s Response
  3. Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
  • API Policy attributes[ pluggable aspects ]: renderer_classes, parser_classes, authentication_classes, throttle_classes, permission_classes, content_negotiation_class
  • Dispatch method[ need to occur before or after calling the handler methods ]: initial, handle_exception, initialize_request, finalize_response

Generic Views

One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.

The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.

If the generic views don’t suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.

Generic API View

This class extends REST framework’s APIView class, adding commonly required behavior for standard list and detail views.

Each of the concrete generic views provided is built by combining GenericAPIView, with one or more mixin classes.

The following attributes control the basic view behavior.

  • queryset
  • serializer_class

Mixin

The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.

ViewSets

Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.

A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().

class UserViewSet(viewsets.ViewSet):

def list(self, request):
pass

def create(self, request):
pass

def retrieve(self, request, pk=None):
pass

def update(self, request, pk=None):
pass

def partial_update(self, request, pk=None):
pass

def destroy(self, request, pk=None):
pass

viewsets.ReadOnlyModelViewSet

  • mixins.ListModelMixin : list() 함수
  • mixins.RetrieveModelMixin : retrieve() 함수 [ 특정 레코드 ]

viewsets.ModelViewSet

  • mixins.ListModelMixin : list() 함수
  • mixins.RetrieveModelMixin : retrieve() 함수
  • mixins.CreateModelMixin : create() 함수
  • mixins.UpdateModelMixin : update() 함수, partial_update() 함수 [fetch]
  • mixins.DestroyModelMixin : destroy() 함수

Routers

REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.

Serializers

Serializer

  • Serialize: query set, model instance → (json, xml로 쉽게 바뀔 수 있는) native python data types [ byte 형태로 변환하는 기술 ]
  • Deserialize: datastream → [ is_valid( ) ] → Python native datatype
  • Saving Instance → create, update
  • Dealing with nested Objects → Serializer class is itself a type of Field

Model Serializer

  • Serializer를 상속받음
  • Model Fields에 대응하는 Serializer Class를 자동으로 생성해준다.
  • Validator 를 자동으로 생성해줍니다. [ unique_together ]
  • create, update 실행을 디폴트로 포함한다.

Authentication [ 유저 식별 ]

Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with.

  • SessionAuthentication
    세션을 통한 인증 여부 체크
    APIView를 통해 디폴트 지정

Permissions [ 각 요청에 대한 허용 / 거부 ]

The permission and throttling policies can then use those authentication credentials to determine if the request should be permitted.

  • AllowAny : 인증여부에 상관없이 뷰 호출 허용 (default)
  • IsAuthenticated : 인증된 요청에 한해서 뷰호출 허용

Exception

REST framework’s views handle various exceptions, and deal with returning appropriate error responses. Subclasses of APIException raised inside REST framework.

  • ParseError: Raised if the request contains malformed data when accessing request.data.
  • NotFound: Raised when a resource does not exists at the given URL.
  • AuthenticationFailed: Raised when an incoming request includes incorrect authentication.
  • PermissionDenied: Raised when an authenticated request fails the permission checks.

Status Codes

# Successful - 2xx
HTTP_200_OK
HTTP_201_CREATED
HTTP_202_ACCEPTED
HTTP_204_NO_CONTENT
# redirection - 3xx
# client error - 4xx
HTTP_400_BAD_REQUEST
HTTP_401_UNAUTHORIZED
HTTP_402_PAYMENT_REQUIRED
HTTP_403_FORBIDDEN
HTTP_404_NOT_FOUND
HTTP_405_METHOD_NOT_ALLOWED
# server error - 5xx
HTTP_500_INTERNAL_SERVER_ERROR

--

--

SoniaComp

Data Engineer interested in Data Infrastructure Powering Fintech Innovation (https://www.linkedin.com/in/sonia-comp/)