• 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组件
  • 相关阅读:
    淘宝如何做智能化UI测试?
    摸爬滚打16年的软件测试经验,建议收藏!
    QA如何高效参与技术设计评审
    官宣!新冠疫苗全民免费接种,全部费用政府出!
    2021年第一次,送Python好书
    【Python】自动化抢购茅台,真香。
    3年以上测试工程师,你的出路在哪里?
    性能测试的目的与类型
    Burpsuite的简单应用-y-Proxy
    用Burpsuite破解网站密码
  • 原文地址:https://www.cnblogs.com/iyouyue/p/8746942.html
Copyright © 2020-2023  润新知