zoukankan      html  css  js  c++  java
  • Django REST_framework Quickstart

    局部避免crsf的方式

    针对视图函数:

    from django.views.decorators.csrf import csrf_exempt
    @csrf_exempt 
    def foo(request):
        return HttpResponse("foo")

    针对CBV:

    # 方式1  在类上方使用
    @method_decorator(csrf_exempt,name="dispatch")
    class IndexView(View):
        # 方式2  在类的 dispatch 方法上使用 @csrf_exempt
        @method_decorator(csrf_exempt)
        def dispatch(self, request, *args, **kwargs):
        print("hello world")
        # 执行父类的dispatch方法                        
            res=super(IndexView,self).dispatch(request, *args, **kwargs)
            print("hello boy")
            return res          
                        

    在url中配置:

    from django.views.decorators.csrf import csrf_exempt
    
    urlpatterns = [
        url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'),
    ]

     rest_framework的简单示例

    以books为例:
    
    (1)创建表,数据迁移
    (2)创建表序列化类BookSerializer
    class BookSerializer(serializers.HyperlinkedModelSerializer):
    	class Meta:
    		model=Book
    		fields="__all__"
     
    (3)创建视图类:
      class BookViewSet(viewsets.ModelViewSet):
    		queryset = Book.objects.all()
    		serializer_class = BookSerializer
    
    (4) 设计url:
     router.register(r'books', views.BookViewSet)

    APIview

    from rest_framework.views import APIView
    
    class APIView(View):    
        def as_view():     
            view = super(APIView, cls).as_view(**initkwargs)  #  self.dispatch
            
        def dispatch():
             # 重新封装request
             request = self.initialize_request(request, *args, **kwargs)
             self.request = request
             
            # 初始化操作
            self.initial(request, *args, **kwargs)
                
            if request.method.lower() in self.http_method_names: 
           # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] handler = getattr(self, request.method.lower(),self.http_method_not_allowed)
           # handler=self.get response = handler(request, *args, **kwargs) # self.get(request, *args, **kwargs) 1 CBV : as_view dispatch 2 掌握API源码流程: as_view dispatch 3 serializers组件
  • 相关阅读:
    java list随机截取(洗牌)
    LINUX安装Docker及Portainer可视化界面
    总结一些选题
    深入理解BIO、NIO、AIO
    InnoDB和MyISAM存储引擎的区别
    MyBatis的解析和运行原理
    [杂项/无聊向]《美食大战老鼠》强卡最优策略搜索代码(非玩家勿入)
    CSP 2019 游记
    NOI 2019 游记
    Comet OJ
  • 原文地址:https://www.cnblogs.com/iyouyue/p/8746942.html
Copyright © 2011-2022 走看看