Django DRF의 Throttling (최대 호출횟수 제한)

cloud_park·2023년 9월 30일
0

DRF를 배우자

목록 보기
4/6

OPEN API 서비스등을 한다면..? 필요할지도...
https://www.django-rest-framework.org/api-guide/throttling/

용어 정리

  • Rate : 지정 기간 내에 허용할 최대 호출 횟수
  • Scope : 각 Rate에 대한 별칭 (alias)
  • Throttle : 특정 조건 하에 최대 호출횟수를 결정하는 로직이 구현된 클래스

기본 제공 Throttle

  • AnonRateThrottle : 인증요청에는 제한을 두지 않고, 비읹으 요청에는 IP단위로 횟수 제한
    scope : 'anon'
  • UserRateThrottle : 인증에는 유저단위로 횟수를 제한하고, 비인증 요청에는 IP단위로 횟수제한
    scope : 'user'
  • ScopedRateThrottle : 인증 요청에는 유저단위로 횟수를 제한하고, 비인증 요청에는 IP단위로 횟수 제한. 각 APIView 내에 throttle_scope 설정을 익어 APIView별로 서로 다른 Scope 적용.

설정 예시

settings.py
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES' : [
        'rest_framework.throttling.UserRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES' : {
        'user' : '10/day',     
				# Rate는 숫자/간격으로 간격은 첫글자만 사용. 
				# d,day,ddd 모두 Day, s,m,h,d가 가능 
    }
}
views.py
from rest_framework.throttling import AnonRateThrottle

class PostViewSet(ViewSet):
    throttle_classes = AnonRateThrottle

최대 호출 횟수 제한을 넘긴다면?

429 Too many Requests 응답.
예외 메시지에 API 활용이 가능한 시점을 알려준다.

profile
Now in progress of untitled advance

0개의 댓글