之前我们用的Django的视图函数叫FBV(也就是函数型视图函数),这里我们来试试CBV(类视图函数)的写法。类视图函数可以让代码看起来更简洁,用起来更方便。
CBV的简单使用
-
视图类
pythonclass BookView(View): def get(self, request): return HttpResponse("get请求book") def post(self, request): return HttpResponse("post请求book")
-
路由:
pythonurlpatterns = [ path('book/', views.BookView.as_view()), ]
-
postman测试get请求:
-
postman测试post请求:
CBV的源码解析
##### 继承
```python
class Animal(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.sleep() # 一定要明确self是谁
def sleep(self):
print("sleeping...")
class Dog(Animal):
def wangwang(self):
print("旺旺叫")
def sleep(self):
print("仰天睡...")
d = Dog("alex", 23)
```
##### 反射
```python
class Animal(object):
def __init__(self, name, age, init_func_str):
self.name = name
self.age = age
func = getattr(self, init_func_str)
func()
def sleep(self):
print("sleeping...")
class Dog(Animal):
def wangwang(self):
print("旺旺叫")
def sleep(self):
print("仰天睡...")
d = Dog("alex", 23, "sleep")
```
#### CBV的源码解析
```python
''''
class BookView(View):
def get(self, request):
return HttpResponse("get请求book")
def post(self, request):
return HttpResponse("post请求book")
class View:
@classonlymethod
def as_view(cls):
def view(request):
self = cls()
return self.dispatch(request, *args, **kwargs)
return view
def dispatch(self, request):
handler = getattr(self, request.method.lower()) # 按请求方式分发
return handler(request, *args, **kwargs)
# 路由
path('book/', views.BookView.as_view()),
path('book/', View.view),
# 一旦用户发起请求,比如get请求访问/book/,得到的是get方法的响应结果
get请求访问/book/ => view() => dispatch() => get()
''''
```