django之基于类的视图和基于函数的视图

时间:2022-11-2    作者:benojan    分类: django


    1. Django中的路由可以对应一个函数,也可以对应一个类。

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('test.html', views.test), # 对应函数,FBA
    path('login.html', views.Login.as_view()), # 对应类,CBA
]

views.py

def test(request):
    return HttpResponse('Hello Test')

from django.views import View
class Login(View):
    def dispatch(self, request, *args, **kwargs): # 类似装饰器的功能
        print('before dispatch')
        obj = super(Login, self).dispatch(request, *args, **kwargs)
        print('after dispatch')
        return obj

    def get(self, request): # 查
        return HttpResponse('Hello Get')

    def post(self, request): # 增
        return HttpResponse('Hello Post')

    def put(self, request): # 改
        return HttpResponse('Hello Put')

    def delete(self, request): # 删
        return HttpResponse('Hello Delete')

标签: django 视图 CBV FBV