drf之请求与响应、drf之视图组件、2个视图基类
drf之请求与响应
Request
REST framework 传入视图的request对象不再是Django默认的HttpRequest对象,而是REST framework提供的扩展了HttpRequest类的Request类的对象。
REST framework 提供了Parser解析器,在接收到请求后会自动根据Content-Type指明的请求数据类型(如JSON、表单等)将请求数据进行parse解析,解析为类字典[QueryDict]对象保存到Request对象中。
Request对象的数据是自动根据前端发送数据的格式进行解析之后的结果。
无论前端发送的哪种格式的数据,我们都可以以统一的方式读取数据。
Request类:属性或方法
data:POST、PUT、PATCH请求方式解析后的数据
原生django,put提交的数据在request.POST中是取不到的,将它转换为以json格式的字符串存放在了body中再取出来
query_params
其他的用起来跟之前一样(FILES、method、path...)底层原理 __getattr__
Response
REST framework提供了一个响应类Response,使用该类构造响应对象时,响应的具体数据内容会被转换(render渲染)成符合前端需求的类型。
REST framework提供了Renderer 渲染器,用来根据请求头中的Accept(接收数据类型声明)来自动转换响应数据到对应格式。如果前端请求中未进行Accept声明,则会采用默认方式处理响应数据,我们可以通过配置来修改默认响应格式。
Response类:属性或方法
data = None,字典、列表序列化成json格式字符串,返回给前端(放在了http响应的body中了)
status = None,http的响应的状态码,默认是200,201(创建成功)
drf 帮我们把所有的Http响应状态码都做成了常量,可以直接导进来用
headers = None,http的响应头,字典
原生的django要在响应头中加数据
res=JsonResponse(d)
res['rrr'] = 'yyyy'
return res
template_name = None,在浏览器中看到好看的页面,指定的模板
content_type = None,响应的编码格式(json)
案例分析
import json
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class Test(APIView):
def get(self, request):
d = {'name': 'lisa', 'hobby': 'run'}
# return HttpResponse(json.dumps(d))
# return JsonResponse(d)
# return Response(d, status=status.HTTP_400_BAD_REQUEST, headers={'name': 'jason'}) 响应头添加数据,状态码修改
# 原生Django给响应头里添加数据,使用下面的方法:
info = HttpResponse(json.dumps(d))
info['age'] = '18'
return info
drf能够解析的请求编码,响应编码
响应状态码
# 正常返回信息1xx
HTTP_100_CONTINUE
HTTP_101_SWITCHING_PROTOCOLS
# 返回成功2xx
HTTP_200_OK
HTTP_201_CREATED
HTTP_202_ACCEPTED
HTTP_203_NON_AUTHORITATIVE_INFORMATION
HTTP_204_NO_CONTENT
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT
HTTP_207_MULTI_STATUS
# 重定向3xx
HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
HTTP_302_FOUND
HTTP_303_SEE_OTHER
HTTP_304_NOT_MODIFIED
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT
# 客户端错误4xx
HTTP_400_BAD_REQUEST
HTTP_401_UNAUTHORIZED
HTTP_402_PAYMENT_REQUIRED
HTTP_403_FORBIDDEN
HTTP_404_NOT_FOUND
HTTP_405_METHOD_NOT_ALLOWED
HTTP_406_NOT_ACCEPTABLE
HTTP_407_PROXY_AUTHENTICATION_REQUIRED
HTTP_408_REQUEST_TIMEOUT
HTTP_409_CONFLICT
HTTP_410_GONE
HTTP_411_LENGTH_REQUIRED
HTTP_412_PRECONDITION_FAILED
HTTP_413_REQUEST_ENTITY_TOO_LARGE
HTTP_414_REQUEST_URI_TOO_LONG
HTTP_415_UNSUPPORTED_MEDIA_TYPE
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
HTTP_417_EXPECTATION_FAILED
HTTP_422_UNPROCESSABLE_ENTITY
HTTP_423_LOCKED
HTTP_424_FAILED_DEPENDENCY
HTTP_428_PRECONDITION_REQUIRED
HTTP_429_TOO_MANY_REQUESTS
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
# 客户端错误5xx
HTTP_500_INTERNAL_SERVER_ERROR
HTTP_501_NOT_IMPLEMENTED
HTTP_502_BAD_GATEWAY
HTTP_503_SERVICE_UNAVAILABLE
HTTP_504_GATEWAY_TIMEOUT
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
HTTP_507_INSUFFICIENT_STORAGE
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
请求编码
能够解析的请求编码
默认能够解析:urlencoded、form-data、json
其实通过配置完成:项目没有配置,是在drf内置的配置文件中提前好了
drf也是有俩套的:
一套是项目中得配置(settings.py),一套是默认的配置
drf的配置文件settings.py中有DEFAULT_PARSER_CLASSES(默认的解析类)
-'rest_framework.parsers.JSONParser', 可以解析json格式
-'rest_framework.parsers.FormParser', 可以解析urlencoded格式
-'rest_framework.parsers.MultiPartParser' 可以解析form-data格式
想让我们的接口只能接受json格式
方式一:全局配置---》项目配置文件---》以后所有的接口都遵循这个配置
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
# 'rest_framework.parsers.FormParser',
# 'rest_framework.parsers.MultiPartParser',
],
}
方式二:局部配置
class TestView(APIView):
parser_classes = [JSONParser,FormParser,MultiPartParser]
总结
解析类的使用顺序:优先用视图类自己的,然后用项目配置文件,最后用内置的
实际项目如何配置:
-基本上都运行JSONParser,FormParser
-如果上传文件只允许MultiPartParser
响应编码
# 如果用浏览器,好看的样子,如果用postman看到json格式
-默认请情况下,响应的编码是根据客户端类型决定的
# 全局配置:在项目的配置文件
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
# 'rest_framework.renderers.JSONRenderer', # json格式
'rest_framework.renderers.BrowsableAPIRenderer', #浏览器的格式
]
}
# 局部配置:
class TestView(APIView):
renderer_classes = [JSONRenderer,]
# 实际编码中,响应一般不配,就用默认
drf之视图组件
由于drf提供了一个顶层的视图类APIView,我们可以通过继承APIView写视图类
后期我们要写的代码可能重复代码比较多,就可以使用面向对象的继承,封装
2个视图基类
# APIView
# GenericAPIView-->继承了APIView
-类属性:
queryset = User.objects.all()
serializer_class = UserSerializer
-方法:
self.get_object() # 根据pk获取单个数据
self.get_serializer # 获取要使用的序列化类
self.get_queryset() # 获取所有要序列化数据
基于APIView写5个接口
class UserView(APIView):
def get(self, request):
book_list = User.objects.all()
ser = UserSerializer(instance=book_list, many=True)
return Response(ser.data)
def post(self, request):
ser = UserSerializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100, 'msg': "新增成功"}, status=201)
else:
return Response({'code': 101, 'msg': ser.errors})
class UserDetailView(APIView):
def get(self, request, pk):
book = User.objects.filter(pk=pk).first()
ser = UserSerializer(instance=book)
return Response(ser.data)
def put(self, request, pk):
book = User.objects.filter(pk=pk).first()
ser = UserSerializer(instance=book, data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100, 'msg': "修改成功"}, status=201)
else:
return Response({'code': 101, 'msg': ser.errors})
def delete(self, request, pk):
User.objects.filter(pk=pk).delete()
return Response('')
基于GenericAPIView写5个接口
from rest_framework.generics import GenericAPIView
class UserView(GenericAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
def get(self, request):
book_list = self.get_queryset()
ser = self.get_serializer(instance=book_list, many=True)
return Response(ser.data)
def post(self, request):
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100, 'msg': "新增成功"}, status=201)
else:
return Response({'code': 101, 'msg': ser.errors})
class UserDetailView(GenericAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
def get(self, request, pk):
book = self.get_object()
ser = self.get_serializer(instance=book)
return Response(ser.data)
def put(self, request, pk):
book = self.get_object()
ser = self.get_serializer(instance=book, data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100, 'msg': "修改成功"}, status=201)
else:
return Response({'code': 101, 'msg': ser.errors})
def delete(self, request, pk):
self.get_queryset().filter(pk=pk).delete()
return Response('')
作业
# 使用GenericAPIView写出book的5个接口,使用面向对象,写5个父类, 继承GenericAPIView+某几个父类后,就有某几个接口
class RetrieveOne():
def get(self, request, pk):
book = self.get_object()
ser = self.get_serializer(instance=book)
return Response(ser.data)
class Retrieve():
def get(self, request):
book_list = self.get_queryset()
ser = self.get_serializer(instance=book_list, many=True)
return Response(ser.data)
class AddData():
def post(self, request):
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100, 'msg': '新建成功'}, status=201)
else:
return Response({'code': 101, 'msg': ser.errors})
class Update():
def put(self, request, pk):
book = self.get_object()
ser = self.get_serializer(instance=book, data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100, 'msg': '修改成功'}, status=201)
else:
return Response({'code': 101, 'msg': ser.errors})
class Remove():
def delete(self, request, pk):
self.get_queryset().filter(pk=pk).delete()
return Response('')
class RetrieveOneModel(GenericAPIView, RetrieveOne):
pass
class RetrieveModel(GenericAPIView, Retrieve):
pass
class AddDataModel(GenericAPIView, AddData):
pass
class UpdateModel(GenericAPIView, Update):
pass
class RemoveModel(GenericAPIView, Remove):
pass
class AddRetrieve(GenericAPIView, Retrieve, AddData):
pass
class RetrieveOneUpdate(GenericAPIView, RetrieveOne, Update):
pass
class UpdateRemove(GenericAPIView, Update, Remove):
pass
class RemoveRetrieveOne(GenericAPIView, RetrieveOne, Remove):
pass
class BookView(AddRetrieve):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetailView(RemoveRetrieveOne):
queryset = Book.objects.all()
serializer_class = BookSerializer