[1,127 | Day67] 글로벌 주파수 성분의 로컬 구성 (소스 코드 분석)

로컬 주파수 성분 구성

1, 요청이 먼저 입력 와서 urls.py파일을

url(r'^book_cbv/', views.Book_cbv.as_view(),name="test3"),

2, 입력 Book_cbv클래스를위한 모습 as_view이 방법은,이 클래스는 우리 자신의 정의, 우리는 단순히 쓰기하지 as_view 방법을

class Book_cbv(APIView):
 
    def get(self,request):
        query_list = models.Book.objects.all()
        # bs = book_serializers(query_list,many=True)
        bs = bookmodelserializer(query_list,many=True,context={'request': request})
 
 
        return Response(bs.data)
    def post(self,request):
        bs = bookmodelserializer(data=request.data)
        print(request.data)
        if bs.is_valid():
            print(bs.validated_data)
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

3에 부모 상대 as_view 방법, 부모 클래스 APIView, as_view의 부모 클래스가 실제로 수행 APIView 클래스 부모 클래스의 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(APIView, cls).as_view(**initkwargs)
    view.cls = cls
    view.initkwargs = initkwargs

4, 모양 as_view 방법을 무엇을했는지 부모 클래스보기 클래스 APIView 클래스로, View 클래스의 실제 구현 as_view 방법은 파견 APIView 클래스의 구현 방법

@classonlymethod
 def as_view(cls, **initkwargs):
     """
     Main entry point for a request-response process.
     """
     for key in initkwargs:
         if key in cls.http_method_names:
             raise TypeError("You tried to pass in the %s method name as a "
                             "keyword argument to %s(). Don't do that."
                             % (key, cls.__name__))
         if not hasattr(cls, key):
             raise TypeError("%s() received an invalid keyword %r. as_view "
                             "only accepts arguments that are already "
                             "attributes of the class." % (cls.__name__, key))
 
     def view(request, *args, **kwargs):
         self = cls(**initkwargs)
         if hasattr(self, 'get') and not hasattr(self, 'head'):
             self.head = self.get
         self.request = request
         self.args = args
         self.kwargs = kwargs
         return self.dispatch(request, *args, **kwargs)
     view.view_class = cls
     view.view_initkwargs = initkwargs
 
     # take name and docstring from class
     update_wrapper(view, cls, updated=())
 
     # and possible attributes set by decorators
     # like csrf_exempt from dispatch
     update_wrapper(view, cls.dispatch, assigned=())
     return view

5 사실, 우리는 여기에 초점을 맞출 필요가 같은 디스패치 방법 APIView에이다 initial방법

def dispatch(self, request, *args, **kwargs):
    """
    `.dispatch()` is pretty much the same as Django's regular dispatch,
    but with extra hooks for startup, finalize, and exception handling.
    """
    self.args = args
    self.kwargs = kwargs
    request = self.initialize_request(request, *args, **kwargs)
    self.request = request
    self.headers = self.default_response_headers  # deprecate?
 
    try:
        self.initial(request, *args, **kwargs)
 
        # Get the appropriate handler method
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                              self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
 
        response = handler(request, *args, **kwargs)
 
    except Exception as exc:
        response = self.handle_exception(exc)
 
    self.response = self.finalize_response(request, response, *args, **kwargs)
    return self.response

6, 초기 접근 방식에 여기에 우리의 주파수 성분에check_throttles

IMG

도 7을 참조하면, 입력 check_throttles방법

def check_throttles(self, request):
    """
    Check if request should be throttled.
    Raises an appropriate exception if the request is throttled.
    """
    for throttle in self.get_throttles():
        if not throttle.allow_request(request, self):
            self.throttled(request, throttle.wait())

8, 다음 봐 get_throttles방법, 우리는 매우 분명하지 않다 여기에서 볼?

우리의 뷰 클래스를 정의 할 필요가 throttle_classe목록, 내용 목록은 각 주파수 성분의 객체 클래스의 예입니다

def get_throttles(self):
    """
    Instantiates and returns the list of throttles that this view uses.
    """
    return [throttle() for throttle in self.throttle_classes]

9, 주파수 구성 요소가 있어야합니다 allow_requestfalse를 반환하는 경우이 메소드가 true를 돌려주는 경우, 방법을, 주파수에 의한 인증, 다음, 더 패스 주파수 성분이 없습니다.

말했다 주파수가 여기에 시간의 단위로 횟수를 사용자가 방문하는 웹 페이지를 의미합니다, 우리는 여기에 단순히 논리의 주파수를 결정하기 위해, 그것을 달성하기 위해 여기에 초점이되지 있습니다

class throttlerate(object):
    def allow_request(self,request,view):
        return True

뷰 클래스 (10), 주파수 성분

class Book_cbv(APIView):
    authentication_classes = []
    permission_classes = [SVIPpermission(),]
    throttle_classes = [throttlerate(),]
    def get(self,request):
        query_list = models.Book.objects.all()
        # bs = book_serializers(query_list,many=True)
        bs = bookmodelserializer(query_list,many=True,context={'request': request})

글로벌 구성의 두 번째 주파수 성분

(1), 글로벌 전역 설정 권한 주파수 성분이 거의 동일한 구성 요소를 별도의 문서에서의 주파수 설정 구성 요소

IMG

2 키 값이 결정

IMG

3, 어셈블리 구성 설정의 도입의 주파수

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES":(
        "app1.utils.Book_auther",
    ),
    "DEFAULT_PERMISSION_CLASSES_CLASSES": (
        "app1.utils.SVIPpermission",
    ),
    "DEFAULT_DEFAULT_THROTTLE_CLASSES_CLASSES": (
        "app1.utils.throttlerate",
    )
}

IMG

추천

출처www.cnblogs.com/fxyadela/p/11941777.html