Home  >  Article  >  Backend Development  >  Example explanation of Django's FBV and CBV

Example explanation of Django's FBV and CBV

不言
不言forward
2019-03-06 14:54:431951browse

This article brings you an example explanation of Django's FBV and CBV. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

FBV: function base views, which is to use functions in views to process requests.

urlpatterns = [
    path('index/', views.index),
]
# 视图函数里
def index(request):
    return render(request,"index.html")

CBV: class base views, which is to use classes in views to handle requests.

urlpatterns = [
    path("login/",views.LoginView.as_view())
]
# 视图函数里
class LoginView(View):

    def dispatch(self, request, *args, **kwargs):
        """
        重写dispatch方法, 可以放一些专属于LoginView的操作
        """
        return ...

    def get(self,request):
        return HttpResponse("OK")

    def post(self,request):
        return HttpResponse("OK")

    def put(self,request):
        return HttpResponse("OK")

    def delete(self,request):
        return HttpResponse("OK")

Source code analysis of CBV:

Django’s url assigns a request to a callable function, not a class. In response to this problem, class-based view (that is, Django's basic View class) provides a static method (that is, a class method) of as_view(). Calling this method will create a class through self = cls(**initkwargs) instance, and then call the dispatch() method through the instance. The dispatch() method will call the corresponding method to process the request (such as get(), post(), etc.) according to the different methods of the request. At this point, these methods are almost the same as function-based views. They need to receive requests and get a response back. If the method is not defined, an HttpResponseNotAllowed exception will be thrown.

Why is there a CBV model?

An important feature of python is object-oriented. And cbv can better reflect the object-oriented nature of Python. cbv implements view methods through classes. Compared with function, class can make better use of the specificity of polymorphism (polymorphism: the same operation can be used on objects of different types), so it is easier to abstract the more common functions in the project from a macro level.

The above is the detailed content of Example explanation of Django's FBV and CBV. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete