django系列3.3--CBV 和 FBV

一.CBV和FBV

FBV function base views 用函數方法來處理請求html

from django.http import HttpResponse
  
	def my_view(request):
	if request.method == 'GET':
        return HttpResponse('OK')
	
	CBV class base views 用類來處理請求(面向對象)
	
	from django.http import HttpResponse
	from django.views import View
  
	class MyView(View):
	
		def get(self, request):
			return HttpResponse('OK')

CBV class base views 用類來處理請求(面向對象) views.pypython

from django.http import HttpResponse
	from django.views import View
  
	class MyView(View):
	
		def get(self, request):
			return HttpResponse('OK')

urls.pydjango

from django.conf.urls import url
from myapp.views import MyView #引入咱們在views.py裏面建立的類

urlpatterns = [
     url(r'^index/$', MyView.as_view()),
]

<br/> CBV傳參,和FBV相似,有名分組,無名分組app

第一種url寫法:無名分組的函數

url(r'^cv/(\d{2})/', views.MyView.as_view(),name='cv'),
url(r'^cv/(?P<n>\d{2})/', views.MyView.as_view(name='xxx'),name='cv')

若是想給類的name屬性賦值,前提你的MyView類裏面必須有name屬性(類屬性,定義init方法來接受屬性行不通,可是能夠自行研究一下,看看如何行通,意義不大),而且以前類裏面的name屬性的值會被覆蓋掉 類寫法post

class MyView(View):
    name = 'robertx'

    def get(self,request,n):
        print('get方法執行了')
        print('>>>',n)
        return render(request,'cvpost.html',{'name':self.name})

    def post(self,request,n):
        print('post方法被執行了')
        return HttpResponse('post')

第二種url寫法: 也能夠在url中指定類的屬性(在url中設置類的屬性Python)url

urlpatterns = [
	url(r'^index/$', MyView.as_view(name="robertx")),   # 類裏面必須有name屬性,而且會被傳進來的這個屬性值給覆蓋掉
]

<br/>spa

二.給視圖函數加裝飾器

寫一個裝飾器:code

def wrapper(func):
		def inner(*args, **kwargs):
			start_time = time.time()
			ret = func(*args, **kwargs)
			end_time = time.time()
			print("used:", end_time-start_time)
		return ret
	return inner

<br/>htm

1.使用裝飾器裝飾FBV

#添加班級
	@wrapper
	def add_class(request):
		if request.method == "POST":
			class_name = request.POST.get("class_name")
			models.Classes.objects.create(name=class_name)	
			return redirect("/class_list/")
		return render(request, "add_class.html")

<br/>

2.使用裝飾器裝飾CBV

from django.views import View
	from django.utils.decorators import method_decorator
		
	class AddClass(View):
		
		@method_decorator(wrapper)
		def get(self, request):
			return render(request, "add_class.html")
			
		def post(self, request):
			class_name = request.POST.get("class_name")
			return redirect("/class_list/")

整體來講有三種方式:

from django.utils.decorators import method_decorator
from django.views import View

@method_decorator(wrapper,name='get')#CBV版裝飾器方式一
class BookList(View):
    @method_decorator(wrapper) #CBV版裝飾器方式二
    def dispatch(self, request, *args, **kwargs):
        print('請求內容處理開始')
        res = super().dispatch(request, *args, **kwargs)
        print('處理結束')
        return res
    def get(self,request):
        print('get內容')
        # all_books = models.Book.objects.all()
        return render(request,'login.html')
    @method_decorator(wrapper) #CBV版裝飾器方式三
    def post(self,request):
        print('post內容')
        return redirect(reverse('book_list'))

<br/>

3.dispatch() 分發的方式處理函數

請求過來以後會先執行dispatch()方法,若是須要批量對具體的請求處理方法.如get,post等作一些操做的時候,能夠手動改寫dispatch方法,這個dispatch方法就和在FBV上加裝飾器同樣

class Login(View):    
	def dispatch(self, request, *args, **kwargs):
    	print('before')
        obj = super(Login,self).dispatch(request, *args, **kwargs)
        print('after')
        return obj
 
    def get(self,request):
        return render(request,'login.html')
     
    def post(self,request):
        print(request.POST.get('user'))
        return HttpResponse('Login.post')
相關文章
相關標籤/搜索