[1127 | Day67] Global and local configuration of the frequency components (source code analysis)

A local frequency component configuration

1, a request come, first enter the urls.pyfile

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

2, enter Book_cbvthe class, look for as_viewthe method, this class is the definition of our own, we simply do not write as_view method

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, into the parent Looking as_view method, the parent class APIView, as_view parent class is actually performed APIView class the parent class's viewmethods

@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, into the parent class View class APIView class, what did look as_view method, the actual implementation as_view method of the View class is the implementation of dispatch APIView class method

@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, into the dispatch method APIView like, in fact, we need to focus on here is the initialmethod

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, into the initial approach here to our frequency componentscheck_throttles

img

7, enter the check_throttlesmethod

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, look at the following get_throttlesmethod, we see here is not very clear?

We need to define a view class in throttle_classethe list, the content list is an example of an object class of each frequency component

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

9, the frequency components must have allow_requesta method, if this method returns true, the certification by the frequency, if it returns false, then there is no pass frequency components.

Said frequency here means the number of times a user visits a web page in a unit of time, we are here simply to achieve it, to determine the frequency of logic is not the focus here

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

10, frequency components in the view class

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})

Second, the frequency components of the global configuration

1, and global global settings set permissions frequency components are almost the same components, the frequency components in a separate document

img

2, the key value is determined

img

3, the frequency of introduction of the assembly configuration settings in

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

Guess you like

Origin www.cnblogs.com/fxyadela/p/11941777.html