一 drf之请求响应回顾
-请求对象:data,query_params,其他跟之前一样,FILES
-默认:支持三种编码
-局部配置:视图类中
-from rest_framework.parsers import JSONParser, FormParser, MultiPartParser
-parser_classes = [JSONParser]
-全局配置:
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
],
}
-全局使用了,局部再换---》视图类改即可
-Response ---》一定继承了django原生的HTTPResponse
-data:字典,列表,字符串,空赋值给它---》http响应体中
-status:http响应状态码 from rest_framework import status
-headers:响应头
res=HttpResponse() res=render() res=redirect() res=JsonResponse()四件套之一
res['name']='lin'
return res
-响应编码格式---》一般不动
-APIView---》写了5个接口
-GenericAPIView 继承自APIView---》以后跟数据库打交道和要序列化就用它
-queryset:以后放所有某个表查询出的数据
-serializer_class:要序列化的类
-get_queryset :要序列化的所有数据,qs对象
-get_serializer :序列化类
-get_object :修改,查询,删除 的单条
RetrieveModelMixin,
CreateModelMixin,
DestroyModelMixin,
ListModelMixin,
UpdateModelMixin
二 9个视图子类
from rest_framework.generics import ListAPIView, CreateAPIView, ListCreateAPIView
from rest_framework.generics import RetrieveAPIView, DestroyAPIView, UpdateAPIView
from rest_framework.generics import RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, RetrieveUpdateAPIView
queryset = Publish.objects.all()
serializer_class = PublishSerializer
1 视图类
class PublishView(ListCreateAPIView):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
class PublishDetailView(RetrieveUpdateDestroyAPIView):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
class PublishView(CreateAPIView):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
class PublishDetailView(RetrieveAPIView):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
class PublishView(GenericAPIView,CreateModelMixin):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
def post(self,request,*args,**kwargs):
return self.create(request,*args,**kwargs)
class PublishDetailView(GenericAPIView,RetrieveModelMixin):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
def get(self,request,*args,**kwargs):
return self.retrieve(request,*args,**kwargs)
2 路由
path('publish/', PublishView.as_view()),
path('publish/', PublishView.as_view()),
三 视图集
1 ModelViewSet
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
path('publish/', PublishView.as_view({'get':'list','post':'create'})),
path('publish/', PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
1.1 ModelViewSet源码分析
-get--list----》拿到所有数据,序列化--返回
-post---create---》之前咱们写的新增的代码一样的
2 ViewSetMixin
-path('publish/', PublishView.as_view({'get':'list','post':'create'}))
-path('publish/', PublishView.as_view({'get':'lqz'}))
-class GenericViewSet(ViewSetMixin, generics.GenericAPIView):ViewSetMixin必须放前面--》保证执行的as_view是ViewSetMixin的
-请求来了,路由匹配成功---》执行ViewSetMixin的as_view内的view(request)
def view(request, *args, **kwargs):
self = cls(**initkwargs)
self.action_map = actions
for method, action in actions.items():
handler = getattr(self, action)
setattr(self, method, handler)
return self.dispatch(request, *args, **kwargs)
-路由中这样配置:PublishView.as_view({'get':'list','post':'create'})
-以后get请求过来,本质执行的就是视图类中的list方法
2.1 以后视图类中方法名可以随意命名,只要路由做好映射
3 ReadOnlyModelViewSet
4 视图层中类的总结
-APIView和GenericAPIView
-APIView的执行流程:包装了新的 处理了csrfrequeset,执行了3大认证,处理全局异常
-GenericAPIView:要做序列化,要跟数据库打交道,就直接继承它即可
-queryset
-serializer_class
-get_object
-get_queryset
-get_serializer
-快速使用5个接口
-某几个接口:查询单条,新增一条,的接口--->使用5个视图扩展类+GenericAPIView
class PublishView(GenericAPIView,CreateModelMixin)
queryset=Publish.objects.all()
serializer_class=序列化类
def post(self,request)
return self.create(request)
class PublishDetailView(GenericAPIView,RetrieveModelMixin)
queryset=Publish.objects.all()
serializer_class=序列化类
def get(self,request)
return self.retrieve(request)
ListAPIView, CreateAPIView
ListCreateAPIView
RetrieveAPIView, DestroyAPIView, UpdateAPIView
RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, RetrieveUpdateAPIView
-ModelViewSet:
-ViewSetMixin+GenericAPIView+5个视图扩展类
-GenericViewSet+5个视图扩展类
-ViewSetMixin源码:路由做映射的配置,以后视图类中方法可以随便命名
-Viewset:ViewSetMixin+APIView---》不需要序列化,路由写法变了
-GenericViewSet:ViewSetMixin+GenericAPIView--》需要序列化,需要用数据库,路由写法变化
-ReadOnlyModelViewSet:list和retrieve
四 drf之路由
path('books/', BookView.as_view())
{'get': 'list', 'post': 'create'}
{'get': 'retrieve', 'put': 'update', 'delete': 'destroy'}
使用方式
from rest_framework.routers import SimpleRouter, DefaultRouter
router = SimpleRouter()
router.register('publish', PublishView, 'publish')
router.register('user',UserView,'user')
urlpatterns = urlpatterns + router.urls
path('api/v1/', include(router.urls)),
1 SimpleRouter, DefaultRouter
SimpleRouter, DefaultRouter区别
-DefaultRouter生成的路径多一个根路径 api-root
-DefaultRouter会多附带一个默认的API根视图,返回一个包含所有列表视图的超链接响应数据
以后就用:SimpleRouter就可以
2 action装饰器
-这些方法需要排除5个 :create,list,destroy,update,retrieve
@action(methods=['POST'],detail=False)
def register(self, request):
return Response('register')
http://127.0.0.1:8008/user/register/---->post--->就会执行register
-methods请求方式,可以写多个
-detail:路径中是否带id号
http://127.0.0.1:8008/user/register/
http://127.0.0.1:8008/user/4/register/
*********************** 代码展示 ***********************************
-1.路由
from django.contrib import admin
from django.urls import path
from app01.views import UserView
from rest_framework.routers import SimpleRouter, DefaultRouter
router = SimpleRouter()
router.register('user', UserView, 'user')
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', UserView.as_view({'post': 'register'})),
]
urlpatterns += router.urls
-2.视图函数
from rest_framework.decorators import action
class UserView(GenericViewSet):
@action(methods=['POST'], detail=True)
def register(self, request, pk):
print(pk)
return Response('register')
3 以后继承ModelViewSet也可也能会重写好多方法
class PublishView(ModelViewSet):
queryset = Publish.objects.all()
serializer_class = PublishSerializer
def list(self, request, *args, **kwargs):
res=super().list(request, *args, **kwargs)
return Response({'code':100,'msg':'成功','result':res.data})
def get_serializer_class(self):
print(self.action)
if self.request.method=='POST':
return WritePublishSerializer
else:
return self.serializer_class
def perform_create(self, serializer):
serializer.save()
4 视图类的对象中的action参数
print(self.action)
importlib的使用
`importlib` 是 Python 标准库中的一个模块,它提供了一种动态导入模块和获取模块信息的方式,
允许你在运行时加载、导入和使用 Python 模块。这对于编写可扩展、灵活的代码和插件系统非常有用。
以下是一些 `importlib` 模块的常见用法示例:
1. **动态导入模块**:
import importlib
module_name = "my_module"
my_module = importlib.import_module(module_name)
result = my_module.my_function()
2. **从模块中导入对象**:
import importlib
module_name = "my_module"
my_module = importlib.import_module(module_name)
my_function = getattr(my_module, "my_function")
result = my_function()
3. **重新加载模块**:
import importlib
module_name = "my_module"
my_module = importlib.import_module(module_name)
my_module = importlib.reload(my_module)
4. **获取模块的文件路径**:
import importlib
module_name = "my_module"
my_module = importlib.import_module(module_name)
module_path = my_module.__file__
这些示例演示了如何使用 `importlib` 动态导入模块、从模块中导入对象、
重新加载模块以及获取模块的文件路径。
这些功能可以用于构建插件系统、模块化应用程序和动态加载模块的需求。
五、GenericViewSet相关流程图
1.GenericViewSet继承流程图
2.minix和GenericViewSet流程图
3.minix和GenericViewSet关系详情流程图
六、rest_framework导图