drf源码继承管理
# drf继承关系
View
APIView
as_view:
执行父类的as_view
调用dispatch
dispatch
init_request
request.queryparams
request.Data
init
内容协商/版本
认证/授权/限流
GenericAPIView
get_queryset
get_serializerclass
过滤/分页
viewset
重写as_view方法
drf系列参考
# drf和orm耦合度太高? 可以继承viewsets.ViewSet类.逃脱了gennericapiview
class ViewSet(ViewSetMixin, views.APIView):pass
class GetTaskIpLogViewSet(viewsets.ViewSet):
def list(self, request, *args, **kwargs):
data = get_task_ip_log("cat /etc/hosts")
return Response(data)
序列化器
api参考
//序列化api: 后端 -> 浏览器
serializer = CommentSerializer(comment) # 对象/queryset -> dict
serializer.data
# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
from rest_framework.renderers import JSONRenderer
json = JSONRenderer().render(serializer.data) # 多个对象many=true
json
# b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'
//反序列化api: 浏览器 -> 后端
# 准备字节流
from django.utils.six import BytesIO
from rest_framework.parsers import JSONParser
stream = BytesIO(json)
data = JSONParser().parse(stream)
serializer = CommentSerializer(data=data) # 多个对象many=true
serializer.is_valid()
# True
serializer.validated_data
serializer.errors
// 校验post参数的合法性
# 还可以自定义复杂的验证器 1.基于字段 2.基于对象 3.全局定义验证器
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
from rest_framework import viewsets
class UserViewset(viewsets.ViewSet):
def list(self, request, *args, **kwargs):
return Response("hello")
def create(self, request, *args, **kwargs):
serializer = CommentSerializer(data=request.data, many=True)
if serializer.is_valid(raise_exception=True): # 抛出404.默认不写是200
return Response(serializer.validated_data)
else:
return Response(serializer.errors)