REST framework는 APIView 클래스를 제공한다
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)
다음과 같은 속성을 이용하여 API views을 다방면에서 컨트롤 할 수 있다.
API policy를 instantiate하기 위한 메소드
핸들러 메소드를 발송하기 전에 다음의 메소드를 부른다.
다음의 메소드는 view의 .dispatch() 메소드를 통해 직접 부를 수 있다. .get(), .post(), .put(), patch(), .delete() 등의 핸들러 메소드를 부르기 전후로 가능
일반적인 function based view.
@api_view(http_method_names=['GET'])
api_view decorator: 뷰가 리스폰스해야하는 HTTP 메소드 리스트를 인수로 받음
1. 기본적인 뷰: 디폴트로 GET 메소드만 허용
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view()
def hello_world(request):
return Response({"message": "Hello, world!"})
@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!"})
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])
def view(request):
return Response({"message": "Hello for today! See you tomorrow!"})
APIView의 다른 decorator들: 모든 decorator는 list/tuple의 인자 하나만 받음
디폴트 스키마를 override하려면 @schema decorator를 사용해야 한다
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!"})
@api_view(['GET'])
@schema(None)
def view(request):
return Response({"message": "Will not appear in schema!"})
참고: Django REST framework - Views document