001---CBV和restful规范

Posted xjmlove

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了001---CBV和restful规范相关的知识,希望对你有一定的参考价值。

CBV 和 restful规范

知识点准备:

django的view

  • FBV:基于函数的视图
  • CBV:基于类的视图

    urls.py
    
    from django.urls import path
    from app01.views import StudentsView
    
    urlpatterns = [
    path('students/ ',StudentsView.as_view()),
    ]
    
    views.py
    
    from django.views import View
    from django.shortcuts import HttpResponse
    
    class StudentsView(View):
    
        def get(self,request,*args,**kwargs):
            return HttpResponse('GET 请求')
    
        def post(self,request,*args,**kwargs):
            return HttpResponse('POST 请求')

csrf_token

  • 原理:基于中间件的process__view()做的,用户发送get请求的时候django会给他返回一个随机字符串,下次用户发送post请求的时候,要求携带这个随机字符串,验证是否一样,
  • 免除:csrf_exempt
  • 验证:csrf_protect
  • 为什么不写在process__request()里面?
    因为它中间件要判断视图函数有没有加免除或者验证的装饰器,如果在request里面,他无法获取哪些视图函数加了装饰器。
    # 第一种:给方法加
    from django.views import View
    from django.views.decorators.csrf import csrf_exempt, csrf_protect
    from django.utils.decorators import method_decorator
        
        
    class StudentsView(View):
    
        @method_decorator(csrf_exempt)
        def dispatch(self, request, *args, **kwargs):
            return super(StudentsView, self).dispatch(request, *args, **kwargs)
        
        def get(self, request, *args, **kwargs):
            
            print('GET')
            return HttpResponse('GET请求')
        
        def post(self, request, *args, **kwargs):
            return HttpResponse('POST请求')
             
    # 第二种:给类加
    @method_decorator(csrf_exempt,name='dispatch')
    class TeachersView(View):
    
        def get(self, request, *args, **kwargs):
            print('GET')
            return HttpResponse('GET请求')
        
        def post(self, request, *args, **kwargs):
            return HttpResponse('POST请求')
           

CBV源码剖析

  • FBV 和 CBV
    基于反射实现根据请求方式不同,执行不同的方法
    原理:
    • 路由 cls.as_view()-->view()-->self.dispatch()-->反射
    • 视图:get post delete put……
    • 流程
       class StudentsView(View):
    
           def dispatch(self, request, *args, **kwargs):
               # return HttpResponse('dispath')
               func = getattr(self,request.method.lower())
               return func(request, *args, **kwargs)
    
           def get(self, request, *args, **kwargs):
               return HttpResponse('GET请求')
    
           def post(self, request, *args, **kwargs):
               return HttpResponse('POST请求')
    
           def delete(self,request,*args,**kwargs):
               return HttpResponse('DELETE请求')
    
           def put(self,request,*args,**kwargs):
               return HttpResponse('PUT请求')
    • 继承(多个类共用的功能,避免重复编写)
       class MyBaseView(object):
           def dispatch(self, request, *args, **kwargs):
               print('before')
               func = super(MyBaseView, self).dispatch(request, *args, **kwargs)
               print('after')
               return func
    
    
       class StudentsView(MyBaseView, View):
    
           def get(self, request, *args, **kwargs):
               print('GET')
               return HttpResponse('GET请求')
    
           def post(self, request, *args, **kwargs):
               return HttpResponse('POST请求')
    
           def delete(self, request, *args, **kwargs):
               return HttpResponse('DELETE请求')
    
           def put(self, request, *args, **kwargs):
               return HttpResponse('PUT请求')

    restful规范

    十条规范

    • API与用户的通信协议:https
    • 域名:
      • URL方式:www.abc.com/api/
      • 子域名方式(存在跨域问题) :www.abc.com www.api.abc.com
    • 版本:www.abc.com/api/v1/
    • 面向资源(视网络上的任何数据为资源,均使用名词、可复数):www.abc.com/api/v1/order/
    • 过滤,通过url传递搜索条件
    • 根据method不同进行不同的操作
      from django.urls import path
      from app01.views import OrderView
    
      urlpatterns = [
          path('order/',OrderView.as_view()),
      ]
    
      class OrderView(View):
    
          def get(self, request, *args, **kwargs):
              return HttpResponse('获取订单')
    
          def post(self, request, *args, **kwargs):
              return HttpResponse('创建订单')
    
          def delete(self, request, *args, **kwargs):
              return HttpResponse('删除订单')
    
          def put(self, request, *args, **kwargs):
              return HttpResponse('更新订单')
    
    • 状态码
    • 错误处理
    • 返回结果
    • 返回结果中就是url

django rest_framework

  • 安装:pip install djangorestframework
  • 使用
    • 认证
      ```python
      from rest_framework.views import APIView
      from rest_framework.exceptions import AuthenticationFailed

        class MyAuthentication(object):
      
            def authenticate(self, request):
      
                token = request._request.GET.get('token')
                # 可以做用户名密码验证
                if not token:
                    raise AuthenticationFailed('认证失败')
                return (1, 2)
      
            def authenticate_header(self, request):
                pass
      
      
        class DogView(APIView):
            authentication_classes = [MyAuthentication]
      
            def get(self, request, *args, **kwargs):
                return HttpResponse('获取小狗')
      
            def post(self, request, *args, **kwargs):
                return HttpResponse('创建小狗')
      
            def delete(self, request, *args, **kwargs):
                return HttpResponse('删除小狗')
      
            def put(self, request, *args, **kwargs):
                return HttpResponse('更新小狗')

      ```

以上是关于001---CBV和restful规范的主要内容,如果未能解决你的问题,请参考以下文章

php Yoast SEO规范输出的代码片段

Django REST框架--认证和权限

restful 架构风格的curd(增删改查)

Spring Rest 文档。片段生成时 UTF-8 中间字节无效 [重复]

RESTful规范

RestFul架构