一:drf之请求与响应
1.Request类
1.继承APIView后,请求对象requests每次请求都是一个新的request
2.data: POST, PUT, PATCH请求方式解析后的数据
3.原生django,put提交的数据在request.POST中是娶不到的
4.其他方法用起来和之前是一样的(method, FILES, path)
2.Response类
参数 | 功能 |
---|---|
data=None | 把字典,列表序列化成json格式字符串,放到http请求的body中,返回给前端 |
status=None | http响应状态码,默认是200, 201 |
headers=None | http的响应头,是字典格式:{‘name’: ‘zhang’} |
template_name=None | 在浏览器中看到好看的页面,指定的模板 |
content_type=None | 响应编码格式(json) |
二.drf能够解析的请求编码,响应编码
1.请求编码
1.默认能解析的请求编码
- urlencoded,form-data, json
2.如何配置请求编码
其实在drf内置的配置文件中提前就配好了请求编码
drf配置文件settings.py中有DEFAULT_PARSER_CLASSES(默认的解析类)
'rest_framework.parsers.JSONParser', 可以解析json格式
'rest_framework.parsers.FormParser', 可以解析urlencoded格式
'rest_framework.parsers.MultiPartParser' 可以解析form-data格式
方式一:全局配置
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
# 'rest_framework.parsers.FormParser',
# 'rest_framework.parsers.MultiPartParser',
],
}
方式二:局部配置
from rest_framework.parsers import JSONParser, FormParser, MultiPartParser
class TestView(APIView):
parser_classes = [JSONParser,FormParser,MultiPartParser]
2.响应编码
如果用浏览器接收响应,看到的是好看的页面,如果用postman,看到的是json格式
默认情况下,响应的编码是根据客户端类型决定的
方式一:全局配置
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
# 'rest_framework.renderers.JSONRenderer', # json格式
'rest_framework.renderers.BrowsableAPIRenderer', #浏览器的格式
]
}
方式二:局部配置
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
class TestView(APIView):
renderer_classes = [JSONRenderer,]
三:drf之视图组件
1.由于drf提供了一个顶层的视图类APIView,以后直接继承APIView写视图类即可
2.后期可以使用面向对象的继承,封装
四:2个视图基类
1.APIView
2.GenericAPIView(继承了APIView)
3.方法:
方法 | 作用 |
---|---|
self.get_object() | 根据pk获取单个数据 |
self.get_serializer() | 获取要使用的序列化类 |
self.get_queryset() | 获取所有要序列化的数据 |
作业:
一:继承GenericAPIView,实现5个接口
models.py
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.CharField(max_length=32)
publish = models.CharField(max_length=32)
serializer.py
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
views.py文章来源:https://www.toymoban.com/news/detail-411060.html
class BookView(GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def get(self, request):
book_list = self.get_queryset()
ser = self.get_serializer(instance=book_list, many=True)
return Response(data=ser.data)
def post(self, request):
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)
else:
return Response(ser.errors)
class BookDetailView(GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
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(ser.data)
else:
return Response({'code': 100, 'msg': '修改成功'})
def delete(self, request, pk):
self.get_queryset().filter(pk=pk).delete()
return Response('ok')
urls.py文章来源地址https://www.toymoban.com/news/detail-411060.html
path('books/', views.BookView.as_view()),
path('books/<int:pk>/', views.BookDetailView.as_view()),
二:2 使用面向对象,写5个父类, 继承GenericAPIView+某几个父类后,就有某几个接口
- 方法一:
class CheckOne(GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def get(self, request, pk):
book = self.get_object()
ser = self.get_serializer(instance=book)
return Response(ser.data)
class CheckAll(GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def get(self, request):
book_list = self.get_queryset()
ser = self.get_serializer(instance=book_list, many=True)
return Response(data=ser.data)
class AddOne(GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def post(self, request):
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)
else:
return Response(ser.errors)
class ChangeOne(GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
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(ser.data)
else:
return Response({'code': 100, 'msg': '修改成功'})
class DeleteOne(GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def delete(self, request, pk):
self.get_queryset().filter(pk=pk).delete()
return Response('ok')
class BookView(CheckAll, AddOne):
def __init__(self):
super(CheckAll, self).__init__()
super(AddOne, self).__init__()
class BookDetailView(CheckOne, ChangeOne, DeleteOne):
def __init__(self):
super(CheckOne, self).__init__()
super(ChangeOne, self).__init__()
super(DeleteOne, self).__init__()
- 方法二:
class CheckOne:
def get(self, request, pk):
book = self.get_object()
ser = self.get_serializer(instance=book)
return Response(ser.data)
class CheckAll:
def get(self, request):
book_list = self.get_queryset()
ser = self.get_serializer(instance=book_list, many=True)
return Response(data=ser.data)
class AddOne:
def post(self, request):
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)
else:
return Response(ser.errors)
class ChangeOne:
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(ser.data)
else:
return Response({'code': 100, 'msg': '修改成功'})
class DeleteOne:
def delete(self, request, pk):
self.get_queryset().filter(pk=pk).delete()
return Response('ok')
class BookView(GenericAPIView, CheckAll, AddOne):
queryset = Book.objects.all()
serializer_class = BookSerializer
def __init__(self):
super(CheckAll, self).__init__()
super(AddOne, self).__init__()
class BookDetailView(GenericAPIView, CheckOne, ChangeOne, DeleteOne):
queryset = Book.objects.all()
serializer_class = BookSerializer
def __init__(self):
super(CheckOne, self).__init__()
super(ChangeOne, self).__init__()
super(DeleteOne, self).__init__()
三:写9个视图子类
# Create your views here.
# 1:查看一条数据
class CheckOne:
def get(self, request, pk):
book = self.get_object()
ser = self.get_serializer(instance=book)
return Response(ser.data)
# 2:查看所有数据
class CheckAll:
def get(self, request):
book_list = self.get_queryset()
ser = self.get_serializer(instance=book_list, many=True)
return Response(data=ser.data)
# 3.增加一条数据
class AddOne:
def post(self, request):
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)
else:
return Response(ser.errors)
# 4:修改一条数据
class ChangeOne:
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(ser.data)
else:
return Response({'code': 100, 'msg': '修改成功'})
# 5:删除一条数据
class DeleteOne:
def delete(self, request, pk):
self.get_queryset().filter(pk=pk).delete()
return Response('ok')
# 6:查看所有+增加一条
class GetAllandPost(CheckAll, AddOne):
def __init__(self):
super(CheckAll, self).__init__()
super(AddOne, self).__init__()
# 7:查看一条+修改一条
class GetOneandPut(CheckOne, ChangeOne):
def __init__(self):
super(CheckOne, self).__init__()
super(ChangeOne, self).__init__()
# 8:查看一条+删除一条
class GetOneandDelete(CheckOne, DeleteOne):
def __init__(self):
super(CheckOne, self).__init__()
super(DeleteOne, self).__init__()
# 9:删除一条+修改一条
class DeleteandPut(DeleteOne, ChangeOne):
def __init__(self):
super(DeleteOne, self).__init__()
super(DeleteOne, self).__init__()
# class BookView(GenericAPIView, CheckAll, AddOne):
# queryset = Book.objects.all()
# serializer_class = BookSerializer
# def __init__(self):
# super(CheckAll, self).__init__()
# super(AddOne, self).__init__()
# class BookDetailView(GenericAPIView, CheckOne, ChangeOne, DeleteOne):
# queryset = Book.objects.all()
# serializer_class = BookSerializer
# def __init__(self):
# super(CheckOne, self).__init__()
# super(ChangeOne, self).__init__()
# super(DeleteOne, self).__init__()
class BookDetailView(GenericAPIView,GetOneandPut):
queryset = Book.objects.all()
serializer_class = BookSerializer
def __init__(self):
super(CheckOne, self).__init__()
super(ChangeOne, self).__init__()
class BookView(GenericAPIView, GetAllandPost):
queryset = Book.objects.all()
serializer_class = BookSerializer
def __init__(self):
super(GetAllandPost, self).__init__()
到了这里,关于drf之day04: drf请求与响应,drf能够解析的请求编码,响应编码,drf之视图组件,2个视图基类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!