【一】项目改名
-
重命名目录
-
重命名项目
- 设置--语言和框架--Django:配置正确的 Django项目根、设置
-
改项目文件夹名
- 需使用全局替换,将原本的项目名替换成新的项目名
- 重新配置Django服务器
【二】模块与包导入规则
1)介绍
- 模块:就是一个py文件
- 脚本:可直接右键运行的py文件
- 包:含有
__init__.py
的文件夹
2)导入规则
-
绝对导入
-
导入的根是环境变量,若路径在环境变量中,可直接以此路径为根导入
-
打印环境变量:
print(sys.path)
-
[ # 项目目录 'E:\\Python\\0\\djangoProject_day3', 'E:\\Python\\0\\djangoProject_day3', # python自带模块(os,time...) 'E:\\Python\\Py3.10.8\\python310.zip', 'E:\\Python\\Py3.10.8\\DLLs', 'E:\\Python\\Py3.10.8\\lib', 'E:\\Python\\Py3.10.8', # 下载的第三方模块 'E:\\Python\\Py3.10.8\\lib\\site-packages', ]
-
-
相对导入
- 相对于的是当前py文件
【三】断言
1)使用
name = 'abc'
if name != 'abc':
raise ValueError('name错误')
print(name)
# -------------等价于-----------
name = 'abc'
assert name == 'abc', 'name错误'
print(name)
- 使用位置
- 确定某些值的功能或类型等
【四】drf之请求响应
1)drf请求
- 支持三种编码格式
- 取出请求体的内容
request.data
- 取出请求体的内容
1.局部使用
-
在视图类(views)上配置如下内容
from rest_framework.parsers import JSONParser, FormParser,MultiPartParser class BookView(APIView): # 只允许json格式 parser_classes = [JSONParser]
2.全局使用
-
在
settings.py
内配置如下内容REST_FRAMEWORK = { # 请求:发送的编码格式 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ] }
3.使用顺序
- 优先:视图类 中配置的
parser_classes
- 其次:项目配置 中
REST_FRAMEWORK
下的DEFAULT_PARSER_CLASSES
- 默认:drf内置的,三个全支持
2)drf响应
- 控制返回的编码格式
1.局部使用
-
在视图类上配置如下内容
from rest_framework.renderers import JSONRenderer class BookViewSet(APIView): # 以json格式显示出来 renderer_classes = [JSONRenderer]
2.全局使用
-
在
settings.py
内配置如下内容REST_FRAMEWORK = { # 响应:返回展示的编码格式 'DEFAULT_RENDERER_CLASSES':[ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] }
【五】视图基类 APIView
-
路由
urlpatterns = [ path('book/', BookViewSet.as_view()), path('book/<int:pk>/', BookDetailViewSet.as_view()) ]
-
视图类
from rest_framework.views import APIView class BookViewSet(APIView): # 查询全部 def get(self, request): books = Book.objects.all() serializer = BookModelSerializer(instance=books, many=True) return Response({'code': 200, 'message': '查询成功', 'data': serializer.data}) # 添加图书 def post(self, request): serializer = BookModelSerializer(data=request.data) # 若出错,停止代码,直接抛出异常 serializer.is_valid(raise_exception=True) serializer.save() return Response({'code': 200, 'message': '添加成功', 'data': serializer.data}) class BookDetailViewSet(APIView): # 查询单个 def get(self, request, pk): book = Book.objects.get(pk=pk) serializer = BookModelSerializer(instance=book) return Response({'code': 200, 'message': '查询成功', 'data': serializer.data}) # 改 def put(self, request, pk): book = Book.objects.get(pk=pk) serializer = BookModelSerializer(instance=book, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({'code': 200, 'message': '修改成功', 'data': serializer.data}) # 删除 def delete(self, request, pk): book = Book.objects.get(id=pk) book.delete() return Response({'code': 200, 'message': '删除成功'})
-
序列化类
class BookModelSerializer(serializers.ModelSerializer): class Meta: model = Book # 获取指定字段 fields = ['name', 'publish', 'author_book', 'publish_data', 'author_book_data'] # 校验书写 extra_kwargs = { 'name': {'min_length': 1, 'max_length': 10}, 'publish': {'write_only':True}, 'author_book': {'write_only':True}, 'publish_data': {'read_only':True}, 'author_book_data': {'read_only':True}, } publish_data = serializers.SerializerMethodField() def get_publish_data(self, obj): return {'name': obj.publish.name, 'addr': obj.publish.addr} author_book_data = serializers.SerializerMethodField() def get_author_book_data(self, obj): authors = obj.author_book.all() list_data = [] for author in authors: list_data.append({'name': author.name, 'gender': author.get_gender_display()}) return list_data
【六】视图基类 GenericAPIView
-
路由,序列化类:不变
-
视图类
from rest_framework.generics import GenericAPIView class BookViewSet(GenericAPIView): ### 要序列化的数据 queryset = Book.objects.all() ### 序列化类 serializer_class = BookModelSerializer # 查询全部 def get(self, request): ### 拿到queryset的值 books = self.get_queryset() serializer = self.get_serializer(instance=books, many=True) return Response({'code': 200, 'message': '查询成功', 'data': serializer.data}) # 添加图书 def post(self, request): ### 拿到serializer_class的值 serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({'code': 200, 'message': '添加成功', 'data': serializer.data}) class BookDetailViewSet(GenericAPIView): queryset = Book.objects.all() serializer_class = BookModelSerializer # 查询单个 def get(self, request, pk): ### 指定pk使用get_object book = self.get_object() serializer = self.get_serializer(instance=book) return Response({'code': 200, 'message': '查询成功', 'data': serializer.data}) # 改 def put(self, request, pk): book = self.get_object() serializer = self.get_serializer(instance=book, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({'code': 200, 'message': '修改成功', 'data': serializer.data}) # 删除 def delete(self, request, pk): self.get_object().delete() return Response({'code': 200, 'message': '删除成功'})
【七】5个视图扩展类
-
需配合GenericAPIView 使用,可定制
-
引入
from rest_framework.mixins import ... ListModelMixin:查全部 CreateModelMixin:添加 RetrieveModelMixin:查单个 UpdateModelMixin,:修改 DestroyModelMixin:删除
-
路由,序列化类:不变
-
视图类
from rest_framework.generics import GenericAPIView from rest_framework.mixins import ListModelMixin, CreateModelMixin,RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin class BookViewSet(GenericAPIView, ListModelMixin, CreateModelMixin): queryset = Book.objects.all() serializer_class = BookModelSerializer # 查询全部 def get(self, request): return super().list(request) ### 定制示例(查询全部) ''' def get(self, request): res = super().list(request=request) return Response({'code': 200, 'msg': '查询成功', 'data': res.data}) ''' # 添加图书 def post(self, request): return super().create(request) class BookDetailViewSet(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin): queryset = Book.objects.all() serializer_class = BookModelSerializer # 查询单个 def get(self, request, pk): return super(BookDetailViewSet, self).retrieve(request, pk) # 改 def put(self, request, pk): return super(BookDetailViewSet, self).update(request, pk) # 删除 def delete(self, request, pk): return super(BookDetailViewSet, self).destroy(request, pk)
【八】9个视图子类
-
引入
from rest_framework.generics import ... ListAPIView:查询全部 CreateAPIView:添加 RetrieveAPIView:查询单个 UpdateAPIView:修改 DestroyAPIView:删除 ListCreateAPIView:查询全部,添加 RetrieveUpdateDestroyAPIView:查询单个,修改,删除 RetrieveUpdateAPIView:查询单个,修改 RetrieveDestroyAPIView:查询单个,删除
-
路由,序列化类:不变
-
视图类
from rest_framework.generics import ListCreateAPIView from rest_framework.generics import RetrieveUpdateDestroyAPIView class BookViewSet(ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookModelSerializer ### 定制示例(查询全部) def list(self, request, *args, **kwargs): res = super().list(request=request) return Response({'code': 200, 'msg': '查询成功', 'data': res.data}) class BookDetailViewSet(RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookModelSerializer
【九】视图集
- 序列化类:不变
1)5接口
-
路由
from App.views import BookViewSet urlpatterns = [ path('book/', BookViewSet.as_view( {'get': 'list', 'post': 'create'} )), path('book/<int:pk>/', BookViewSet.as_view( {'get': 'retrieve', 'put': 'update', 'delete': 'destroy'} )), ]
-
视图类
from rest_framework.viewsets import ModelViewSet class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookModelSerializer ### 定制示例(查询全部) def list(self, request, *args, **kwargs): res = super().list(request=request) return Response({'code': 200, 'msg': '查询成功', 'data': res.data})
2)2接口(只读)
-
路由
from App.views import BookViewSet urlpatterns = [ path('book/', BookViewSet.as_view({'get': 'list'})), path('book/<int:pk>/', BookViewSet.as_view({'get': 'retrieve'})), ]
-
视图类
from rest_framework.viewsets import ReadOnlyModelViewSet class BookViewSet(ReadOnlyModelViewSet): queryset = Book.objects.all() serializer_class = BookModelSerializer
【十】
GenericAPIView ————》 APIView————》view
标签:get,self,request,接口,视图,data,class,serializer
From: https://www.cnblogs.com/Mist-/p/18336158