CBV

什么是CBV

CBV(class base views) 就是在视图里使用类处理请求

优点

  • 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  • 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性

使用

# urls.py
from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
     url(r'^index/$', MyView.as_view()),
]
# views.py
from django.http import HttpResponse
from django.views import View

class GreetingView(View):
    name = "yuan"
    def get(self, request):
         return HttpResponse(self.name)

# You can override that in a subclass

class MorningGreetingView(GreetingView):
    name= "alex"

results matching ""

    No results matching ""