python笔记(restframework 视图,视图总结)
程序员文章站
2024-03-26 09:57:41
...
-
APIView
class BookView(APIView): pass url(r'^books/$', views.BookView.as_view(),name="books"), 分析走的类的方法: url(r'^books/$', View类下的view,name="books"), 一旦访问books/: view(request)======APIView类下的dispatch()====请求方式对应的示例方法()
from rest_framework.views import APIView,Response from rest_framework import serializers from app01 import models class BooksModelSerializers(serializers.ModelSerializer): class Meta: model = models.Book fields = "__all__" depth = 1 class Bookview(APIView): def get(self,request): book_list = models.Book.objects.all() bs = BooksModelSerializers(book_list,many=True) return Response(bs.data) def post(self,request): bs = BooksModelSerializers(request.data) if bs.is_valid(): return Response()
url(r'^books',views.Bookview.as_view()),
-
访问dispath()过程分析
初始化操作:
(1)构建新的request:self.request=self.initial_request() self.request._request self.request.GET self.request.data
(2) 执行组件
认证,权限,频率 认证:request.user self.initial(request, *args, **kwargs) ====认证组件 self.perform_authentication(request) ==== request.user ===== for authenticator in self.authenticators: # [TokenAuth(),] try: user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise if user_auth_tuple is not None: self._authenticator = authenticator self.user, self.auth = user_auth_tuple return 权限组件 self.check_permissions(request) =========== for permission in self.get_permissions(): if not permission.has_permission(request, self): self.permission_denied( request, message=getattr(permission, 'message', None) ) 频率组件 self.check_throttles(request) ============= for throttle in self.get_throttles(): # [VisitRateThrottle(),] if not throttle.allow_request(request, self): self.throttled(request, throttle.wait()) # 受限制
分发:
if request.method.lower() in self.http_method_names: handler = getattr(self,request.method.lower(), self.http_method_not_allowed) response = handler(request, *args, **kwargs) return response
-
序列化组件
class PublishSerializers(serializers.Serializer): name = serializers.CharField() email = serializers.CharField() class PublishModelSerializers(serializers.ModelSerializer): class Meta: model=Publish fields="__all__" # queryset或者model对象-------------》json数据(get请求) ps=PublishSerializers(queryset,many=True) ps.data # [{},{},{}] ps=PublishSerializers(model_obj,many=False) ps.data # {} # json数据-------》记录 # 添加操作(post请求) ps=PublishSerializers(data=request.data) if ps.is_valid(): ps.save() # create # 更新操作(put请求) ps=PublishSerializers(model_obj,data=request.data) if ps.is_valid(): ps.save() # update
-
视图组件
版本1:(Book表)
url(r'^books/$', views.BookView.as_view(),name="books"), url(r'^books/(\d+)/$', views.BookDetailView.as_view(),name="detailbook"),
class BookView(APIView): def get(self,request): book_list=Book.objects.all() bs=BookModelSerializers(book_list,many=True,context={'request': request}) return Response(bs.data) def post(self,request): # post请求的数据 bs=BookModelSerializers(data=request.data) if bs.is_valid(): print(bs.validated_data) bs.save()# create方法 return Response(bs.data) else: return Response(bs.errors) class BookDetailView(APIView): def get(self,request,id): book=Book.objects.filter(pk=id).first() bs=BookModelSerializers(book,context={'request': request}) return Response(bs.data) def put(self,request,id): book=Book.objects.filter(pk=id).first() bs=BookModelSerializers(book,data=request.data) if bs.is_valid(): bs.save() return Response(bs.data) else: return Response(bs.errors) def delete(self,request,id): Book.objects.filter(pk=id).delete() return Response()
版本2:(mixIn)
url(r'^authors/$', views.AuthorModelView.as_view(), url(r'^authors/(\d+)/$', views.AuthorModelView.as_view(),
from rest_framework import mixins from rest_framework import generics class AuthorView(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView): queryset=Author.objects.all() serializer_class =AuthorModelSerializers def get(self,request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self,request, *args, **kwargs): return self.create(request, *args, **kwargs) class AuthorDetailView(mixins.RetrieveModelMixin,mixins.DestroyModelMixin,mixins.UpdateModelMixin,generics.GenericAPIView): queryset = Author.objects.all() serializer_class = AuthorModelSerializers def get(self,request,*args, **kwargs): return self.retrieve(request,*args, **kwargs) def delete(self,request,*args, **kwargs): return self.destroy(request,*args, **kwargs) def put(self,request,*args, **kwargs): return self.retrieve(request,*args, **kwargs)
版本3:基于通用类
url(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"), url(r'^authors/(?P<pk>\d+)/$', views.AuthorModelView.as_view({"get":"retrieve","put"
from rest_framework import mixins from rest_framework import generics class AuthorView(generics.ListCreateAPIView): queryset=Author.objects.all() serializer_class =AuthorModelSerializers class AuthorDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Author.objects.all() serializer_class = AuthorModelSerializers
版本4
urls.pyurl(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"), url(r'^authors/(?P<pk>\d+)/$', views.AuthorModelView.as_view({"get":"retrieve","put"
class AuthorModelView(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorModelSerializers
整体流程:
url(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"), url(r'^authors/$', ViewSetMixin.as_view({"get":"list","post":"create"}),name="author"), url(r'^authors/$', ViewSetMixin类下的view), 一旦访问 /authors/: ViewSetMixin def view(): for method, action in actions.items(): # {"get":"list","post":"create"} handler = getattr(self, action) # self.list self.create setattr(self, method, handler) self.dispatch(request, *args, **kwargs) APIView类下的self.dispatch # 分发 if request.method.lower() in self.http_method_names: handler = getattr(self,request.method.lower(), self.http_method_not_allowed) response = handler(request, *args, **kwargs) # self.list() return response
上一篇: css的`class`选择器选择前缀.
下一篇: 硬币组合问题