DRF

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

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

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

  • 공식문서에 포함된 디자인 관련 내용

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

  • 중복 피하기

WHAT

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

WHY

  • Serializer 기능: 모델 인스턴스 → JSON형태, Dictionary 형태 직렬화

파이썬의 데이터 타입

  • 실제 데이터 값을 저장하는 원시타입(Primitive type) [boolean, char, 정수, 실수]

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

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

ModelSerializer

  • General Serializer와 차이

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 ]

Responses

Views

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

  1. Django’s HttpRequest → REST framework’s APIView Class
  • API Policy attributes[ pluggable aspects ]: renderer_classes, parser_classes, authentication_classes, throttle_classes, permission_classes, content_negotiation_class

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

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() 함수

viewsets.ModelViewSet

  • mixins.ListModelMixin : list() 함수

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 형태로 변환하는 기술 ]

Model Serializer

  • Serializer를 상속받음

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)

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.

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

I will be a software architect.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store