코드로 우주평화

Function Based Views 본문

나는 이렇게 본다/Django REST framework

Function Based Views

daco2020 2022. 2. 11. 13:16

 

Function Based Views

함수 기반 뷰
Saying [that class-based views] is always the superior solution is a mistake.— Nick Coghlan 클래스 기반 뷰가 항상 우수한 해결책이라고 말하는 것은 실수다.

 

REST framework also allows you to work with regular function based views.

레스트 프레임워크는 너가 일반적인 함수 기반 뷰로도 일할 수 있는 것을 허용한다.

It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than the usual Django HttpRequest) and allows them to return a Response (instead of a Django HttpResponse), and allow you to configure how the request is processed.

그것은 너의 함수 기반 뷰를 감싸는 간단한 데코레이터 세트를 제공하는데, 리퀘스트 인스턴스 수신과 응답 반환을 보장한다. (장고 http리퀘스트나 리스폰 대신) 그리고 너가 리퀘스트를 처리하는 방식을 구성할 수 있다.

@api_view()

Signature: @api_view(http_method_names=['GET'])

The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to.

이 기능의 핵심은 api_view 데코레이터인데, 이는 너의 뷰가 응답해야하는 HTTP 매서드를 취한다.

For example, this is how you would write a very simple view that just manually returns some data:

예를 들어, 이것은 너가 매우 간단하게 작성한 어떤 데이터를 수동으로 반환하는 뷰이다.
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def hello_world(request):
    return Response({"message": "Hello, world!"})

This view will use the default renderers, parsers, authentication classes etc specified in the settings.

이 뷰는 설정안에 있는 기본 렌더러와 파서, 인증 클래스들을 사용할 것이다.

By default only GET methods will be accepted.

기본은 겟 메서드만을 받아들일 것이다.

Other methods will respond with "405 Method Not Allowed".

다른 메서드들은 ‘405 메서드 허용하지 않음’으로 응답할 것이다.

To alter this behaviour, specify which methods the view allows, like so:

이 행동을 바꾸는 것은, 해당 뷰에 다음처럼 메서드들 허용을 지정해야한다.
@api_view(['GET', 'POST'])
def hello_world(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"message": "Hello, world!"})

API policy decorators

api 정책 데코레이터

To override the default settings, REST framework provides a set of additional decorators which can be added to your views.

기본 설정을 재정의 하기 위해서, 레스트 프레임워크는 너의 뷰를 더할 수 있는 추가의 데코레이터 세트를 제공한다.

These must come after (below) the @api_view decorator.

이것들은 @api_view 데코레이터 후(아래)에 와야 한다.

For example, to create a view that uses a throttle to ensure it can only be called once per day by a particular user, use the @throttle_classes decorator, passing a list of throttle classes:

예를 들어 특정 사용자가 스로틀을 사용해 하루에 한 번만 호출할 수 있는 뷰를 만들려면 @throttle_classes 데코레이터를 사용하여 스로틀 클래스 리스트를 전달합니다.*스로틀은 임시 상태를 나타내며 클라이언트가 API에 대해 수행할 수 있는 요청 속도를 제어(조절)하는 데 사용. (액션을 제어 및 조절할 수 있는 것이라고 보면 될 듯)
from rest_framework.decorators import api_view, throttle_classes
from rest_framework.throttling import UserRateThrottle

class OncePerDayUserThrottle(UserRateThrottle):
    rate = '1/day'

@api_view(['GET'])
@throttle_classes([OncePerDayUserThrottle]) # api_view 아래에 기재, 리스트로 전달
def view(request):
    return Response({"message": "Hello for today! See you tomorrow!"})

These decorators correspond to the attributes set on APIView subclasses, described above.

이런 데코레이터들은 위에서 설명한 APIView 하위 클래스 설정의 속성에 해당한다.

 

The available decorators are:

사용가능한 데코레이터는 다음과 같다.
  • @renderer_classes(...) 랜더러 → 어떤 역할?
  • @parser_classes(...) 파서→ 어떤 역할?
  • @authentication_classes(...) 인증
  • @throttle_classes(...) 조절
  • @permission_classes(...) 권한

Each of these decorators takes a single argument which must be a list or tuple of classes.

이런 데코레이터들은 클래스를 리스트나 튜퓰형태로, 하나의 인수로 받는다.

 

데코레이터를 사용하지 않는다면 기본값으로 될 것이고, 만약 커스텀을 위해서는 새로 설정할 값을 클래스로 만든 후, 리스트나 튜플 형태로 데코레이터에 삽입하여 넣어야 하는 것 같다.

View schema decorator

To override the default schema generation for function based views you may use the @schema decorator.

기본 스키마를 재정의하기 위해서는 너가 함수 기반 뷰에서 스키마 데코레이터를 사용할 수 있다.

This must come after (below) the @api_view decorator. For example:

이것은 @api_view 데코레이터 후(아래)에 와야 한다. 예제:
from rest_framework.decorators import api_view, schema
from rest_framework.schemas import AutoSchema

class CustomAutoSchema(AutoSchema):
    def get_link(self, path, method, base_url):
        # override view introspection here...

@api_view(['GET'])
@schema(CustomAutoSchema())
def view(request):
    return Response({"message": "Hello for today! See you tomorrow!"})

This decorator takes a single AutoSchema instance, an AutoSchema subclass instance or ManualSchema instance as described in the Schemas documentation.

이 데코레이터는 스키마 문서안에 설명된대로, 하나의 ‘오토스키마 인스턴스’, ‘오토스키마의 하위클래스 인스턴스’, ‘매뉴얼스키마의 인스턴스’를 받는다.

You may pass None in order to exclude the view from schema generation.

너는 스키마 생성으로부터 뷰를 제외하기위해 None을 보낼 수도 있다.*스키마란? 데이터베이스의 구조와 제약조건에 관해 전반적인 명세를 기술한 것 입니다.
@api_view(['GET'])
@schema(None)
def view(request):
    return Response({"message": "Will not appear in schema!"})

 

 

Summary

  • 데코레이터로 메서드를 받아들인다.(플라스크와 유사)
  • 기본 메서드는 get이다.
  • 메서드가 여러개라면 if로 분기처리하여 사용가능하다.
  • 데코레이터를 추가로 기재하여 기본값들을 커스텀할 수 있다.
  • 예를들어 스로틀(제어)과 스키마(디비명세) 등

 

 

Reference

 

Views - Django REST framework

 

www.django-rest-framework.org

 

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

Generic views - Methods  (0) 2022.02.15
Generic views - Attributes  (0) 2022.02.14
Class-based Views  (0) 2022.02.10