067.Python框架Django之DRF视图类
2021-02-10 22:16
标签:code cfile value content framework image 对比 width des drf除了在数据序列化部分简写代码以外,还在视图中提供了简写操作。所以在django原有的django.views.View类基础上,drf封装了多个子类出来提供给我们使用。 Django REST framwork 提供的视图的主要作用: 请求与响应 REST framework 传入视图的request对象不再是Django默认的HttpRequest对象,而是REST framework提供的扩展了HttpRequest类的Request类的对象。 REST framework 提供了Parser解析器,在接收到请求后会自动根据Content-Type指明的请求数据类型(如JSON、表单等)将请求数据进行parse解析,解析为类字典[QueryDict]对象保存到Request对象中。 Request对象的数据是自动根据前端发送数据的格式进行解析之后的结果。 无论前端发送的哪种格式的数据,我们都可以以统一的方式读取数据。 常用属性: 1. data request.data 返回解析之后的请求体数据。类似于Django中标准的 request.POST 和 request.FILES 属性,但提供如下特性: 包含了解析之后的文件和非文件数据 包含了对POST、PUT、PATCH请求方式解析后的数据 利用了REST framework的parsers解析器,不仅支持表单类型数据,也支持JSON数据 2. query_params request.query_params与Django标准的 request.GET 相同,只是更换了更正确的名称而已。 REST framework提供了一个响应类Response,使用该类构造响应对象时,响应的具体数据内容会被转换(render渲染)成符合前端需求的类型。 REST framework提供了 Renderer 渲染器,用来根据请求头中的Accept(接收数据类型声明)来自动转换响应数据到对应格式。如果前端请求中未进行Accept声明,则会采用默认方式处理响应数据,我们可以通过配置来修改默认响应格式。 可以在rest_framework.settings查找所有的drf默认配置项 构造方式: data数据不要是render处理之后的数据,只需传递python的内建类型数据即可,REST framework会使用 renderer 渲染器处理data。 data不能是复杂结构的数据,如Django的模型类对象,对于这样的数据我们可以使用 Serializer 序列化器序列化处理后(转为了Python字典类型)再传递给data参数。 参数说明: data: 为响应准备的序列化处理后的数据; status: 状态码,默认200; template_name: 模板名称,如果使用HTMLRenderer 时需指明; headers: 用于存放响应头信息的字典; content_type: 响应数据的Content-Type,通常此参数无需传递,REST framework会根据前端所需类型数据来设置该参数。 常用属性(用的不多): 1. data:传给response对象的序列化后,但尚未render处理的数据 2. status_code:状态码的数字 3. content:经过render处理后的响应数据 为了方便设置状态码, REST Framework在rest_framework.status模块中提供了常用状态码常量。 REST framework 提供了众多的通用视图基类与扩展类,以简化视图的编写。 Django REST framwork 提供的视图的主要作用: APIView 是REST framework提供的所有视图的基类,继承自Django的View父类。 APIView 与View的不同之处在于: 支持定义的类属性 在APIView中仍以常规的类视图定义方法来实现get() 、post() 或者其他请求方式的方法。 对比APIview和view的区别 创建新的应用 (drfdemo) root@darren-virtual-machine:~/PycharmProjects/drfdemo/drf_demo# python3 manage.py startapp req 注册app 配置路由分发 (drfdemo) root@darren-virtual-machine:~/PycharmProjects/drfdemo/drf_demo# vim req/urls.py 视图文件 访问对比 http://127.0.0.1:8000/req/student1/ 打印结果 http://127.0.0.1:8000/req/student2/ 打印结果 加参数访问,提取参数结果 访问http://127.0.0.1:8000/req/student1/?name=alex&age=20 和http://127.0.0.1:8000/req/student2/?name=alex&age=20 打印结果 使用responbe定义状态码响应 访问http://127.0.0.1:8000/req/student2/?name=alex&age=20 添加头部信息 访问结果 使用API借口实现功能 url路由配置 新建serializer文件,序列操作 (drfdemo) root@darren-virtual-machine:~/PycharmProjects/drfdemo/drf_demo# vim req/serializers.py 写视图文件 使用POSTMAN调试 获取所有 添加数据 查看数据库 修改数据 查看数据库 删除 数据库查看 状态码 继承自APIView,主要增加了操作序列化器和数据库查询的方法,作用是为下面Mixin扩展类的执行提供方法支持。通常在使用时,可搭配一个或多个Mixin扩展类。 提供的关于序列化器使用的属性与方法 属性:serializer_class 指明视图使用的序列化器 方法:get_serializer_class(self) get_serializer(self, args, *kwargs) 返回序列化器对象,主要用来提供给Mixin扩展类使用,如果我们在视图中想要获取序列化器对象,也可以直接调用此方法。 提供的关于数据库查询的属性与方法 属性:queryset 指明使用的数据查询集 方法:get_queryset(self) 返回视图使用的查询集,主要用来提供给Mixin扩展类使用,是列表视图与详情视图获取数据的基础,默认返回queryset属性,可以重写,例如: get_object(self) 返回详情视图所需的模型类数据对象,主要用来提供给Mixin扩展类使用。 在试图中可以调用该方法获取详情信息的模型类对象。 其他可以设置的属性 url路由 实现5个功能 视图文件 使用POSTMAN调试 获取所有 添加数据 数据库查看 修改数据 查看数据库 删除 数据库 在req应用下的urls.py文件: views视图文件 使用POSTMAN调试 增加数据 数据库 修改数据 数据库 删除数据 url路由文件一 关于视图类的一下概念
1.1 Request请求
1.2 Response响应
REST_FRAMEWORK = {
‘DEFAULT_RENDERER_CLASSES‘: ( # 默认响应渲染类
‘rest_framework.renderers.JSONRenderer‘, # json渲染器
‘rest_framework.renderers.BrowsableAPIRenderer‘, # 浏览API渲染器
)
}
Response(data, status=None, template_name=None, headers=None, content_type=None)
1.3 状态码信息
二 视图
2.1 APIView和View区别
from
rest_framework.views
import
APIView
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘rest_framework‘,
‘students.apps.StudentsConfig‘,
‘ser.apps.SerConfig‘,
‘req.apps.ReqConfig‘,
]
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path(‘student/‘,include("students.urls")),
path(‘ser/‘,include("ser.urls")),
path(‘req/‘, include("req.urls")),
]
from django.urls import path,re_path
from req import views
urlpatterns = [
path(‘student1/‘,views.Student1View.as_view()),
path(‘student2/‘, views.Student2APIView.as_view()),
]
from django.shortcuts import render,HttpResponse
from django.views import View
# Create your views here.
class Student1View(View):
def get(self,request):
print(request)
print(type(request))
return HttpResponse("view1")
class Student2APIView(View):
def get(self,request):
print(request)
print(type(request))
return HttpResponse("view2")
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
# Create your views here.
class Student1View(View):
def get(self,request):
print(request.GET)
print(type(request))
return HttpResponse("view1")
class Student2APIView(APIView):
def get(self,request):
print(request.query_params)
print(type(request))
return HttpResponse("view2")
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
class Student1View(View):
def get(self,request):
print(request.GET)
print(type(request))
return HttpResponse("view1")
class Student2APIView(APIView):
def get(self,request):
print(request.query_params)
print(type(request))
return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
class Student1View(View):
def get(self,request):
print(request.GET)
print(type(request))
return HttpResponse("view1")
class Student2APIView(APIView):
def get(self,request):
print(request.query_params)
print(type(request))
return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"})
使用APIView提供学生信息的5个API接口
GET /req/student3/ # 获取全部数据
POST /req/student3/ # 添加数据
GET /req/student3/(?P
from django.urls import path,re_path
from req import views
urlpatterns = [
path(‘student1/‘,views.Student1View.as_view()),
path(‘student2/‘, views.Student2APIView.as_view()),
# 使用APIView
path("student3/", views.Student3APIView.as_view()),
re_path(r"^student3/(?P
from students.models import Student
from rest_framework import serializers
class StudentModelSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ["id", "name", "age", "sex"]
extra_kwargs = {
"name": {"max_length": 10, "min_length": 4},
"age": {"max_value": 150, "min_value": 0},
}
def validate_name(self, data):
if data == "root":
raise serializers.ValidationError("用户名不能为root!")
return data
def validate(self, attrs):
name = attrs.get(‘name‘)
age = attrs.get(‘age‘)
if name == "alex" and age == 22:
raise serializers.ValidationError("alex在22时的故事。。。")
return attrs
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
class Student1View(View):
def get(self,request):
print(request.GET)
print(type(request))
return HttpResponse("view1")
class Student2APIView(APIView):
def get(self,request):
print(request.query_params)
print(type(request))
return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"})
from students.models import Student
from req.serializers import StudentModelSerializer
class Student3APIView(APIView):
def get(self, request):
"""获取所有数据"""
student_list = Student.objects.all()
# 序列化操作
serializer = StudentModelSerializer(instance=student_list, many=True)
return Response(serializer.data)
def post(self, request):
# 获取用户提交的数据
data_dict = request.data
# 实例化序列化器对象
serializer = StudentModelSerializer(data=data_dict)
# 数据校验
serializer.is_valid(raise_exception=True)
# 保存数据
serializer.save()
return Response(serializer.validated_data)
class Student4APIView(APIView):
def get(self, request, pk):
# 过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
serializer = StudentModelSerializer(instance=student_obj)
return Response(serializer.data)
def put(self, request, pk):
# 过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
# 获取用户提交的数据
data_dict = request.data
serializer = StudentModelSerializer(instance=student_obj, data=data_dict)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.validated_data)
def delete(self, request, pk):
Student.objects.filter(pk=pk).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
2.2 GenericAPIView(通用视图类)
from
rest_framework.generics
import
GenericAPIView
def get_serializer_class(self):
if self.request.user.is_staff:
return FullAccountSerializer
return BasicAccountSerializer
def get_queryset(self):
user = self.request.user
return user.accounts.all()
2.3 GenericAPIView实现接口
from django.urls import path,re_path
from req import views
urlpatterns = [
path(‘student1/‘,views.Student1View.as_view()),
path(‘student2/‘, views.Student2APIView.as_view()),
# 使用APIView
path("student3/", views.Student3APIView.as_view()),
re_path(r"^student3/(?P
使用GenericAPIView提供学生信息的5个API接口
GET /req/student4/ # 获取全部数据
POST /req/student4/ # 添加数据
GET /req/student4/(?P
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
class Student1View(View):
def get(self,request):
print(request.GET)
print(type(request))
return HttpResponse("view1")
class Student2APIView(APIView):
def get(self,request):
print(request.query_params)
print(type(request))
return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"})
from students.models import Student
from req.serializers import StudentModelSerializer
class Student3APIView(APIView):
def get(self, request):
"""获取所有数据"""
student_list = Student.objects.all()
# 序列化操作
serializer = StudentModelSerializer(instance=student_list, many=True)
return Response(serializer.data)
def post(self, request):
# 获取用户提交的数据
data_dict = request.data
# 实例化序列化器对象
serializer = StudentModelSerializer(data=data_dict)
# 数据校验
serializer.is_valid(raise_exception=True)
# 保存数据
serializer.save()
return Response(serializer.validated_data)
class Student4APIView(APIView):
def get(self, request, pk):
# 过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
serializer = StudentModelSerializer(instance=student_obj)
return Response(serializer.data)
def put(self, request, pk):
# 过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
# 获取用户提交的数据
data_dict = request.data
serializer = StudentModelSerializer(instance=student_obj, data=data_dict)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.validated_data)
def delete(self, request, pk):
Student.objects.filter(pk=pk).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
from rest_framework.generics import GenericAPIView
class Student5GenericAPIView(GenericAPIView):
# 当前视图类中操作的公共数据,先从数据库查询出来
queryset = Student.objects.all()
# 设置类视图中所有方法共有调用的序列化器类
serializer_class = StudentModelSerializer
def get(self, request):
# 获取模型数据
student_list = self.get_queryset()
# 调用序列化器
serializer = self.get_serializer(instance=student_list, many=True)
return Response(serializer.data)
def post(self, request):
"""新增数据"""
# 获取用户提交的数据并实例化序列化器对象
serializer = self.get_serializer(data=request.data)
# 数据校验
serializer.is_valid(raise_exception=True)
# 保存数据
serializer.save()
return Response(serializer.data)
class Student6GenericAPIView(GenericAPIView):
# 当前视图类中操作的公共数据,先从数据库查询出来
queryset = Student.objects.all()
# 设置类视图中所有方法共有调用的序列化器类
serializer_class = StudentModelSerializer
def get(self, request, pk):
"""参数pk名,必须要叫pk,否则会报错。"""
# 获取模型对象
instance = self.get_object()
serializer = self.get_serializer(instance=instance)
return Response(serializer.data)
def put(self, request, pk):
instance = self.get_object()
serializer = self.get_serializer(instance=instance, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
def delete(self, request, pk):
# 获取模型对象
instance = self.get_object()
# 删除模型对象
instance.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
2.4 五个视图扩展类
使用GenericAPIView结合视图Mixin扩展类,快速实现数据接口的APIView
ListModelMixin 实现查询所有数据功能
CreateModelMixin 实现添加数据的功能
RetrieveModelMixin 实现查询一条数据功能
UpdateModelMixin 更新一条数据的功能
DestroyModelMixin 删除一条数据的功能
from django.urls import path,re_path
from req import views
urlpatterns = [
path(‘student1/‘,views.Student1View.as_view()),
path(‘student2/‘, views.Student2APIView.as_view()),
# 使用APIView
path("student3/", views.Student3APIView.as_view()),
re_path(r"^student3/(?P
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
class Student1View(View):
def get(self,request):
print(request.GET)
print(type(request))
return HttpResponse("view1")
class Student2APIView(APIView):
def get(self,request):
print(request.query_params)
print(type(request))
return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"})
from students.models import Student
from req.serializers import StudentModelSerializer
class Student3APIView(APIView):
def get(self, request):
"""获取所有数据"""
student_list = Student.objects.all()
# 序列化操作
serializer = StudentModelSerializer(instance=student_list, many=True)
return Response(serializer.data)
def post(self, request):
# 获取用户提交的数据
data_dict = request.data
# 实例化序列化器对象
serializer = StudentModelSerializer(data=data_dict)
# 数据校验
serializer.is_valid(raise_exception=True)
# 保存数据
serializer.save()
return Response(serializer.validated_data)
class Student4APIView(APIView):
def get(self, request, pk):
# 过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
serializer = StudentModelSerializer(instance=student_obj)
return Response(serializer.data)
def put(self, request, pk):
# 过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
# 获取用户提交的数据
data_dict = request.data
serializer = StudentModelSerializer(instance=student_obj, data=data_dict)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.validated_data)
def delete(self, request, pk):
Student.objects.filter(pk=pk).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
from rest_framework.generics import GenericAPIView
class Student5GenericAPIView(GenericAPIView):
# 当前视图类中操作的公共数据,先从数据库查询出来
queryset = Student.objects.all()
# 设置类视图中所有方法共有调用的序列化器类
serializer_class = StudentModelSerializer
def get(self, request):
# 获取模型数据
student_list = self.get_queryset()
# 调用序列化器
serializer = self.get_serializer(instance=student_list, many=True)
return Response(serializer.data)
def post(self, request):
"""新增数据"""
# 获取用户提交的数据并实例化序列化器对象
serializer = self.get_serializer(data=request.data)
# 数据校验
serializer.is_valid(raise_exception=True)
# 保存数据
serializer.save()
return Response(serializer.data)
class Student6GenericAPIView(GenericAPIView):
# 当前视图类中操作的公共数据,先从数据库查询出来
queryset = Student.objects.all()
# 设置类视图中所有方法共有调用的序列化器类
serializer_class = StudentModelSerializer
def get(self, request, pk):
"""参数pk名,必须要叫pk,否则会报错。"""
# 获取模型对象
instance = self.get_object()
serializer = self.get_serializer(instance=instance)
return Response(serializer.data)
def put(self, request, pk):
instance = self.get_object()
serializer = self.get_serializer(instance=instance, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
def delete(self, request, pk):
# 获取模型对象
instance = self.get_object()
# 删除模型对象
instance.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
from rest_framework.mixins import ListModelMixin, CreateModelMixin
class Student7GenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset = Student.objects.all()
serializer_class = StudentModelSerializer
def get(self, request):
#获取所有数据
return self.list(request)
def post(self, request):
#增加数据
return self.create(request)
from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
class Student8GenericAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
queryset = Student.objects.all()
serializer_class = StudentModelSerializer
def get(self, request, pk):
return self.retrieve(request)
def put(self, request, pk):
return self.update(request)
def delete(self, request, pk):
return self.destroy(request)2.5 内置的扩展子类
from django.urls import path,re_path
from req import views
urlpatterns = [
path(‘student1/‘,views.Student1View.as_view()),
path(‘student2/‘, views.Student2APIView.as_view()),
# 使用APIView
path("student3/", views.Student3APIView.as_view()),
re_path(r"^student3/(?P
上一篇:回溯算法