Django Rest Framework 프레임워크 구현

15018 단어
1. 기본 절차
  • url.py
  • from django.conf.urls import url, include
    from web.views.s1_api import TestView
    
    urlpatterns = [
       url(r'^test/', TestView.as_view()),
    ]
    
  • view.py
  • from rest_framework.views import APIView
    from rest_framework.response import Response
     
     
    class TestView(APIView):
        def dispatch(self, request, *args, **kwargs):
            """
                  ,    dispatch  ,dispatch             get/post/put   
             
              :APIView  dispatch          
            """
            return super().dispatch(request, *args, **kwargs)
     
        def get(self, request, *args, **kwargs):
            return Response('GET  ,    ')
     
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
     
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    

    위는restframework 프레임워크의 기본 절차로 중요한 기능은 APIView의dispatch에서 터치하는 것이다.
    2. 인증 및 인증
    a. 사용자 URL이 전송한token 인증
    from django.conf.urls import url, include
    from web.viewsimport TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    

    view.py
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.request import Request
    from rest_framework import exceptions
    
    token_list = [
        'sfsfss123kuf3j123',
        'asijnfowerkkf9812',
    ]
    
    
    class TestAuthentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER()
                    else:
                        self.user = None
            
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            val = request.query_params.get('token')
            if val not in token_list:
                raise exceptions.AuthenticationFailed("      ")
    
            return ('    ', '  token')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            #      ,      WWW-Authenticate    
            pass
    
    
    class TestView(APIView):
        authentication_classes = [TestAuthentication, ]
        permission_classes = []
    
        def get(self, request, *args, **kwargs):
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    

    b. 요청 헤더 설정
  • url.py
  • from django.conf.urls import url, include
    from web.viewsimport TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    

    view.py
    #!/usr/bin/env python # -*- coding:utf-8 -*-
    from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import BaseAuthentication from rest_framework.request import Request from rest_framework import exceptions
    
    token_list = [ 'sfsfss123kuf3j123', 'asijnfowerkkf9812',
    ] class TestAuthentication(BaseAuthentication): def authenticate(self, request): """     ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER()
                    else:
                        self.user = None
    
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed   """
            import base64
            auth = request.META.get('HTTP_AUTHORIZATION', b'') if auth:
                auth = auth.encode('utf-8')
            auth = auth.split() if not auth or auth[0].lower() != b'basic': raise exceptions.AuthenticationFailed('    ') if len(auth) != 2: raise exceptions.AuthenticationFailed('    ')
            username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':') if username == 'alex' and password == '123': return ('    ', '  token') else: raise exceptions.AuthenticationFailed('        ') def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses. """
            return 'Basic realm=api'
    
    class TestView(APIView):
        authentication_classes = [TestAuthentication, ]
        permission_classes = [] def get(self, request, *args, **kwargs): print(request.user) print(request.auth) return Response('GET  ,    ') def post(self, request, *args, **kwargs): return Response('POST  ,    ') def put(self, request, *args, **kwargs): return Response('PUT  ,    ')
    c. 다중 인증 규칙
  • url.py
  • from django.conf.urls import url, include
    from web.views.s2_auth import TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
  • view.py
  • #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.request import Request
    from rest_framework import exceptions
    
    token_list = [
        'sfsfss123kuf3j123',
        'asijnfowerkkf9812',
    ]
    
    
    class Test1Authentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER() #     :    
                    else:
                        self.user = None
    
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()#     :None
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            import base64
            auth = request.META.get('HTTP_AUTHORIZATION', b'')
            if auth:
                auth = auth.encode('utf-8')
            else:
                return None
            print(auth,'xxxx')
            auth = auth.split()
            if not auth or auth[0].lower() != b'basic':
                raise exceptions.AuthenticationFailed('    ')
            if len(auth) != 2:
                raise exceptions.AuthenticationFailed('    ')
            username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':')
            if username == 'alex' and password == '123':
                return ('    ', '  token')
            else:
                raise exceptions.AuthenticationFailed('        ')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            # return 'Basic realm=api'
            pass
    
    class Test2Authentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER() #     :    
                    else:
                        self.user = None
            
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()#     :None
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            val = request.query_params.get('token')
            if val not in token_list:
                raise exceptions.AuthenticationFailed("      ")
    
            return ('    ', '  token')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            pass
    
    
    class TestView(APIView):
        authentication_classes = [Test1Authentication, Test2Authentication]
        permission_classes = []
    
        def get(self, request, *args, **kwargs):
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    

    인증 및 권한
  • urls.py
  • from django.conf.urls import url, include
    from web.views import TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
  • view.py
  • #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.permissions import BasePermission
    
    from rest_framework.request import Request
    from rest_framework import exceptions
    
    token_list = [
        'sfsfss123kuf3j123',
        'asijnfowerkkf9812',
    ]
    
    
    class TestAuthentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER() #     :    
                    else:
                        self.user = None
            
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()#     :None
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            val = request.query_params.get('token')
            if val not in token_list:
                raise exceptions.AuthenticationFailed("      ")
    
            return ('    ', '  token')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            pass
    
    
    class TestPermission(BasePermission):
        message = "      "
    
        def has_permission(self, request, view):
            """
                         
            Return `True` if permission is granted, `False` otherwise.
            :param request: 
            :param view: 
            :return: True   ;False   
            """
            if request.user == "   ":
                return True
    
        # GenericAPIView get_object   
        def has_object_permission(self, request, view, obj):
            """
                GenericAPIView,      get_object      ,          
            Return `True` if permission is granted, `False` otherwise.
            :param request: 
            :param view: 
            :param obj: 
            :return: True   ;False   
            """
            if request.user == "   ":
                return True
    
    
    class TestView(APIView):
        #        request.user  
        authentication_classes = [TestAuthentication, ]
    
        #   
        #          
        permission_classes = [TestPermission, ]
    
        def get(self, request, *args, **kwargs):
            # self.dispatch
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    

    e. 글로벌 사용
    위에서 설명한 작업은 개별 뷰에 대한 특수 구성이며 전역적으로 구성하려면 구성 파일에 쓰기 작업을 다시 수행해야 합니다.
  • setting.py
  • REST_FRAMEWORK = {
        'UNAUTHENTICATED_USER': None,
        'UNAUTHENTICATED_TOKEN': None,
        "DEFAULT_AUTHENTICATION_CLASSES": [
            "web.utils.TestAuthentication",
        ],
        "DEFAULT_PERMISSION_CLASSES": [
            "web.utils.TestPermission",
        ],
    }
    
  • urls.py
  • from django.conf.urls import url, include
    from web.views import TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
  • view.py
  • #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    class TestView(APIView):
    
        def get(self, request, *args, **kwargs):
            # self.dispatch
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    

    좋은 웹페이지 즐겨찾기