cbv源码分析
-视图类,必须继承view
-在views.py写get,post方法,只要get请求来,就会走get方法(方法和之前写的FBV完全一样)
-路由:path('book/',views.book.as_view())---这个函数执行完一定是一个内存地址--》view(闭包函数)内存函数的地址
-请求来了,路由匹配--》view(request)--》self dispatch(self, request, *args, **kwargs)
-dispatch-->把请求方法转成小写(if request.method.lower() in self.http_method_names:)--》通过反射(handler = getattr(self, request.method.lower(), self.http_method_not_allowed)),去对象中找,有没有get方法,有就加括号执行(return handler(request, *args, **kwargs)),并且把request传进去。
APIView源码分析
#核心代码
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
#self.initialize_request(request, *args, **kwargs)request是当次请求的request
#request = self.initialize_request(request, *args, **kwargs) request是一个新的request对象
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
#三大认证模块(request是新的request)
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
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
#响应模块
response = handler(request, *args, **kwargs)
except Exception as exc:
#异常模块
response = self.handle_exception(exc)
#渲染模块
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
Serializer序列化组件
1、序列化,序列化器会把模型对象转换成字典,经过response以后变成了JSON字符串
2、反序列化,把客户端发送过来的数据,经过request以后变成字典,序列化器可以把字典转成模型
3、反序列化,完成数据校验功能
简单使用(要去settings中app注册'rest_framework')
1、写一个序列化的类,继承Serializer
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
name = serializers.CharField()
price = serializers.CharField()
author = serializers.CharField()
publish = serializers.CharField()
2、在类中写要序列化的字段,想序列化那个字段,就在类中写那个字段
name = serializers.CharField()
price = serializers.CharField()
author = serializers.CharField()
publish = serializers.CharField()
3、在视图类中使用,导入---》实例化得到序列化类的对象,把要序列化的对象传入
from rest_framework.views import APIView
from app01.models import Book
from app01.serialize import BookSerializer
from rest_framework.response import Response
class BookView(APIView):
def get(self,request,pk):
book = Book.objects.filter(id=pk).first()
book_serialize = BookSerializer(book)
return Response(book_serialize.data)
4、序列化类的对象.data 是一个字典
book_serialize.data
5、把字典返回,如果不使用rest_framework提供的Response,就得使用JSONResponse
return Response(book_serialize.data)