CBV class view and class view decorator of Django framework

Keywords: Python Django Back-end

preface

Over the past few years, I have been struggling in the it industry. Along the way, many have summarized some high-frequency interviews in the python industry. I see most of the new blood in the industry, and I still have all kinds of difficult questions for the answers to all kinds of interview questions or collection

Therefore, I developed an interview dictionary myself, hoping to help everyone, and also hope that more Python newcomers can really join the industry, so that Python fire does not just stay in advertising.

Wechat applet search: Python interview dictionary

Or follow the original personal blog: https://lienze.tech

You can also focus on WeChat official account and send all kinds of interesting technical articles at random: Python programming learning.

CBV

CBV (class base views) uses classes to process requests in views

In the previous code, our view function is used to respond to the request and return the response. Generally, the request method we need to judge, get or post, requires us to judge the condition through if in the code. This view function is called FBV

But now django also provides a method called CBV, which writes the view function in the class, and sets the traditional get and post judgment as the functions in the class. In this way, when the user initiates different requests, it will automatically enter the corresponding functions in the class, such as the following

from django.views import View
class ArticleView(View):
    def get(self,request):
        raise Http404
    def post(self,request):
        if request.is_ajax():
            id_ = request.POST.get('id_')
            result = models.Article.objects.get(id=id_).content
            data = result.replace('\r\n','<br>') 
            return HttpResponse(json.dumps(data,ensure_ascii=False) )
       	raise Http404

By defining the request type as a function, it is more convenient to judge the request mode

When the user accesses, it will pass the as in the view base class_ View - > dispatch to judge and distribute to different function names corresponding to requests through request types; That is, access through get, and the corresponding function named get will be called

In addition, functions in the class must be lowercase,

  • At this time, the corresponding route is set to, and the as of the attempt class needs to be used_ Instantiate the view function
#url.py
path('article/',ajaxviews.ArticleView.as_view())

Through the class view, it is convenient for us to judge the request conditions

And it can realize the function decoupling and synchronization of the same resource route when using different request access during interface development

It means that you don't have to pile all the functions into one view function. How convenient!

Moreover, in the Django restframework, CBV will also be frequently used for view writing

Class view decorator

When using decorators prepared for function views in class views, you cannot add decorators directly

Method is required_ decorator

from django.utils.decorators import method_decorator

All decoration

from django.views import View
from django.utils.decorators import method_decorator
def my_decorator(func):
    def nei(request): # The dispatch function has the parameter request
        print('This is the decorator calling')
        return func(request)
    return nei
@method_decorator(my_decorator, name='dispatch') # Add decorator for all request methods
class DemoView(View):
    def get(self, request):
        print('get method')
        return HttpResponse('ok')

    def post(self, request):
        print('post method')
        return HttpResponse('ok')

Partial decoration

Just pass the method_ Select the decorated function name for the name parameter of the decorator method

@method_decorator(my_decorator, name='post')
class DemoView(View):
    def get(self, request):
        print('get method')
        return HttpResponse('ok')

    def post(self, request):
        print('post method')
        return HttpResponse('ok')

Specific decoration

You only need to use method on each function_ Decorator decorator

class DemoView(View):
    @method_decorator(my_decorator) # Added decorator for get method
    def get(self, request):
        return HttpResponse('ok')
		@method_decorator(my_decorator) # A decorator has been added to the post method
    def post(self, request):
        return HttpResponse('ok')

Class view csrf_token decoration

When the class view needs to allow cross site submission of data, use csrf_exempt decorator decorator functions can be accessed across domains

However, the above method is used for csrf_exempt does not work. It needs to be decorated on the dispatch function of the base class of the class view

from django.views.decorators.csrf import csrf_exempt
#@method_decorator(csrf_exempt,name='dispatch') # It can also be decorated on the view of directly loading classes
class DemoView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(DemoView,self).dispatch(request, *args, **kwargs)
    def get(self, request):
        print('get method')
        return HttpResponse('ok')
    def post(self, request):
        print('post method')
        return HttpResponse('ok')
  • Note: csrf decoration can only take effect on the dispatch function of class view

In addition to decorating on the dispatch function of the class view, CSRF is used at the route mapping_ It is also possible for exempt function to modify routing rules

#urls.py
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
    ...
    path('',csrf_exempt(ajaxviews.DemoView.as_view()))
]

Posted by skyxmen on Tue, 23 Nov 2021 18:21:19 -0800