一、FBV
FBV(function base views) 就是在视图里使用函数处理请求。
看代码:
urls.py
from django.conf.urls import url, include
# from django.contrib import admin
from mytest import views
urlpatterns = [
# url(r‘^admin/‘, admin.site.urls),
url(r‘^index/‘, views.index),
]
from django.shortcuts import render
def index(req):
if req.method == ‘POST‘:
print(‘method is :‘ + req.method)
elif req.method == ‘GET‘:
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘)
注意此处定义的是函数【def index(req):】
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="A" />
<input type="submit" name="b" value="提交" />
</form>
</body>
</html>
上面就是FBV的使用。
二、CBV
CBV(class base views) 就是在视图里使用类处理请求。
将上述代码中的urls.py 修改为如下:
from mytest import views
urlpatterns = [
# url(r‘^index/‘, views.index),
url(r‘^index/‘, views.Index.as_view()),
]
注:url(r‘^index/‘, views.Index.as_view()), 是固定用法。
将上述代码中的views.py 修改为如下:
from django.views import View
class Index(View):
def get(self, req):
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘)
def post(self, req):
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘)
注:类要继承 View ,类中函数名必须小写。
三、CBV匹配原理
这种根据url来匹配方法的是通过反射方法(getattr)来做的。请求过来后先走dispatch这个方法,这个方法存在View类中。
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
四、定制dispatch
如果需要批量对方法,例如get,post等方法做一些操作的时候,这里我们可以手动写一个dispatch,这个dispatch就和装饰器的效果一样。因为请求来的时候总是先走的dispatch。
from django.views.generic import View
class Cbv(View):
def dispatch(self, request, *args, **kwargs):
print('操作前的操作')
obj = super(Cbv,self).dispatch(request, *args, **kwargs)
print('操作后的操作代码')
return obj
def get(self,request):
# return HttpResponse('cbv-get')
return render(request,'login.html')
def post(self,request):
return HttpResponse('cbv-post')
这次我们在通过浏览器访问的时候,发现不管get或者post方法,都会走print代码。