백엔드 Back-end/장고 Django

Q. 장고Django의 View와 DRF의 APIView의 인증 관련 차이는?

Tap to restart 2023. 1. 15. 09:00
반응형

A. CSRF 보호 제외 여부다.


DRF(Django Rest Framework)의 APIView 자체도 from django.views.generic import View를 상속받아서 만든 것이다. View에 API에 주로 쓰도록 기능이 추가된 형태로 볼 수 있다.

APIView의 as_view 메소드를 보자.

    @classmethod
    def as_view(cls, **initkwargs):
        """
        Store the original class on the view function.

        This allows us to discover information about the view when we do URL
        reverse lookups.  Used for breadcrumb generation.
        """
        if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
            def force_evaluation():
                raise RuntimeError(
                    'Do not evaluate the `.queryset` attribute directly, '
                    'as the result will be cached and reused between requests. '
                    'Use `.all()` or call `.get_queryset()` instead.'
                )
            cls.queryset._fetch_all = force_evaluation

        view = super().as_view(**initkwargs)
        view.cls = cls
        view.initkwargs = initkwargs

        # Note: session based authentication is explicitly CSRF validated,
        # all other authentication is CSRF exempt.
        return csrf_exempt(view)

맨 끝 쪽에 csrf_exempt CSRF 보호 제외 함수가 적용된 것을 볼 수 있다. APIView를 쓰면 일일이 매번 View에다가 csrf_exempt를 적용하지 않아도 되어서 편하다. 단, 세션 인증은 예외다. 세션 인증을 쓸 경우에는 APIView를 쓰더라도 CSRF Token을 요청시 같이 보내거나 따로 추가로 csrf_exempt 적용을 해줘야 한다.

반응형