欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python笔记(restframework 视图,视图总结)

程序员文章站 2024-03-26 09:57:41
...
  1. 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()====请求方式对应的示例方法()
    

    view.py

    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()
    

    urls.py

    url(r'^books',views.Bookview.as_view()),
    
  2. 访问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
    
  3. 序列化组件

       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
    
  4. 视图组件

    版本1:(Book表)

    urls.py

    url(r'^books/$', views.BookView.as_view(),name="books"),
    url(r'^books/(\d+)/$', views.BookDetailView.as_view(),name="detailbook"),
    

    views.py

    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)

    urls.py

    url(r'^authors/$', views.AuthorModelView.as_view(),
    url(r'^authors/(\d+)/$', views.AuthorModelView.as_view(),
    

    views.py

    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:基于通用类

    urls.py

    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"
    

    views.py

    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.py

    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"
    

    views.py

     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
    
相关标签: PYTHON