Views CBV and FBV

This is the 14th day of my participation in the August Text Challenge.More challenges in August

FBV function based view

That's using functions to handle requests in the viewCopy the code

CBV class based view

That is, using classes in the view to handle requests. Python is an object-oriented programming language, and many of the benefits of object-oriented programming are lost (inheritance, encapsulation, polymorphism) if you develop only with functions. So Django added classbased-view later. Let's write a View in a class. The main advantages of this approach are as follows: 1. Improved code reusability and the use of object-oriented techniques such as mixins. You can use different functions for different HTTP methods, rather than a lot of if judgments, to improve code readabilityCopy the code

1, CBV

from django.views import View
​
class xxx(View) :
    
    def get(self,request) :
        # Handle get requests exclusively
        return response
    
    def post(self,request) :
        # Handle POST requests exclusively
        return response
Copy the code
url(r"xx/",xxx.as_view()) As_view () is executed
Copy the code

As_view () process

1. The project runtime loads the urls.py file and executes the class with the as_view() method. 2. When the request arrives, the view function is executedCopy the code

Dispatch method

# http_method_names = ['get'] # Http_method_names overwrites submitted request methods that are called first when the View function is executed internally
def dispatch(self, request, *args, **kwargs) :
    print("Operation before dispatch")
    ret = super().dispatch(request, *args, **kwargs)Execute the dispatch method inside the View
    print("Operation after dispatch")
    return ret
Copy the code

CBV executes the Dispatch method before running the GET and POST methods

2, FBV

# views.py
def register(request) :
    form_obj = RegForm()  Get an empty form
    if request.method == "POST":
        form_obj = RegForm(request.POST, request.FILES)  Get a form with data

        if form_obj.is_valid():
            # register successfully
            form_obj.save()  Because ModelForm is inherited, all can be saved directly
            return redirect("login")

    return render(request, "register.html", {"form_obj": form_obj})
Copy the code
url(r'^register/$', views.register, name="register"),
Copy the code

3. Decorators

3.1 FBV

I just add it to the function

3.2 CBV

You need a decorator

from django.utils.decorators importMethod_decorator Converts a function decorator into a method decorator.Copy the code

Plus the method

@method_decorator(timer)
def get(self, request) :   This is the only way to use the get method
Copy the code

Applied to the dispatch method

 @method_decorator(timer)  All of the request methods defined in # can be used
    def dispatch(self, request, *args, **kwargs) :
        print("Operation before dispatch")
        ret = super().dispatch(request, *args, **kwargs)Execute the dispatch method inside the View
        print("Operation after dispatch")
        return ret
Copy the code

Add in the class

@method_decorator(timer,name="get")
@method_decorator(timer,name="post")
@method_decorator(timer,name="dispatch")
class PublishersAdd(View) :  # add to class, you can specify the corresponding method
Copy the code

Custom decorators

Decorator: timer

# Count time decorator
import time
from functools import wraps
​
def timer(func) :
    @wraps(func)
    def inner(*args, **kwargs) :
        "" inner function ""
        start = time.time()
        ret = func(*args, **kwargs)
        print("Total execution time :{}".format(time.time() - start))
        return ret
​
    return inner
​
@timer
def func() :
    """ I'm a func function """
    time.sleep(0.5)
    print("aaaa")
​
func()
print(func.__name__)  # Wraps (@wraps(func)) # wraps(@wraps(func))
print(func.__doc__) Print comments in the function
Copy the code
from functools import wraps
@wraps(func) Use # wraps to render your own wraps, and comments, otherwise it would render wraps inside the inner wraps
Copy the code