1.CBV 和 FBV
FBV function based view CBV class based view
2. CBV的使用流程
在 view中 導入 from django.views import View
1.建立一個類 繼承父類 View
class Cbv(View):
def get(self,request):
return HttpResponse('Ok!!!')
def post(self,request)
pass
自動判斷請求方法 而執行相對應函數
2. 在路由 url檔案中
url(r'^add_press/$', views.Cbv.as_view())
3.執行原理 views.Cbv.as_view()
三個方法 :as_vieiw---->view---->dispatch-----存在 / 不存在 (請求方法) ----傳回響應
1.在 as_vieiw() 中執行 view 方法 return self.dispatch() -->執行dispatch
dispatch():中 通過 getattr 反射 拿到 子類的 get 或post 方法 給到handler 再傳回執行
1.判斷請求方法 是否存在于 http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
2. 如果存在 就執行子類 中對應的方法(get,post.......)
3.handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
此時handler 就是一個 方法 return handler (request ,*arg,**kwgs) 加括号執行
2.傳回handler 相當于是一個HttpResponse 對象 傳回到django 處理 httpresponse 響應
3.如果請求方法 不存在,則django内置方法 傳回一個 不存在的 HttpResponse 頁面
6. 加裝飾器
FBV 普通加法
@wrapper
def test()
CBV
from django.utils.decorators import method_decorator 使用django 封裝的方法 使用裝飾器
1. 加在方法上
@method_decorator(timer)
def get(self, request):
2. 加在dispatch上 在CBV中隻有加載dispatch 上才有用
@method_decorator(timer)
def dispatch(self, request, *args, **kwargs)
3. 加在類上
@method_decorator(timer,name='post')
@method_decorator(timer,name='get')
class AddPress(View):
7. request 和response
1.request .GET('name') 擷取url中的參數 2.request.POST('name') 擷取 form送出的 或ajax 送出的data資料
3. request. file 擷取上傳檔案 4.request.body資料真正存放的地方
5.request.get_host 6.request.is_ajax
HttpResponse render redirect