六、补充


返回

6.1 CBV

  • views.py

    from django.http import HttpResponse
    from django.views import View
    from django.utils.decorators import method_decorator  # 加装饰器用
      
    # 通过method_decorator方法给get、posts加装饰器
    @method_decorator(装饰器函数名,name='dispatch')
    class Login(View):
      	# 通过method_decorator方法给get、post加装饰器
        @method_decorator(装饰器函数名)
    		def dispatch(self, request, *args, **kwargs):
          	# 相当于给get、post加装饰器
            print('get、post请求之前')
            # 分发器,调用get、post
          	super(Login, self).dispatch(self, request, *args, **kwargs)
            # 相当于给get、post加装饰器
            print('get、post请求之后')
        		return HttpResponse('OK')
        # 单一装饰器
        @method_decorator(装饰器函数名)
        def get(self, request, *args, **kwargs):
            return HttpResponse('OK')
        def post(self, request, *args, **kwargs):
            return HttpResponse('OK')
    
  • urls.py

    # urls.py
    from django.conf.urls import url
    from myapp.views import Login
      
    urlpatterns = [
         url(r'^index/$', Login.as_view()),
    ]
    
返回