Django 백엔드의 모든것

Django, DRF djangorestframework, 로그인 상태 확인하는 방법 handle_exceoption

WinGyu 2024. 4. 12. 10:58

 

from rest_framework.views import APIView
from rest_framework.exceptions import NotAuthenticated
from rest_framework.permissions import IsAuthenticated

from django.shortcuts import redirect


class PageAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def handle_exception(self, exc):
        if isinstance(exc, NotAuthenticated):
            return redirect('login_url')
        return super().handle_exception(exc)

 

아주 간편하게 구현이 가능하다.

 

DRF (DjangoRESTFramwork) 에서 제공하는 APIView에서 사용 가능하다.

 

1. permission_classes 사용하기

permission_classes 을 사용해 기본적으로 자격 검증을 실시한다.

 

2. def handle_exception(self, exc) 사용하기

def handle_exception(self, exc) 을 사용해 사용자를 검증한다. redirect 함수에 로그인 페이지 주소를 작성해주면 된다. (또는 urls name)