DRF Django restframe work 十大组件

2019-08-04  本文已影响0人  Forever_f59e

认证

自定义认证类
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.permissions import BasePermission
    from rest_framework.exceptions import AuthenticationFailed
    from store import models

    class Myauthentication(BaseAuthentication):
        def authenticate(self,request):
           # 实现认证逻辑
           token = request._request.GET.get('token')
           obj = models.Token.objects.filter(token=token).first()
           if obj:
                return (obj.appid,token)
          else:
                raise AuthenticationFailed('认证失败')
局部使用认证类
    REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
]
}

权限

和上面的一样自定义的写好之后,局部使用写permission_classess权限类,全局的使用直接在settings文件配置。

自定义权限

重写has_object_permission方法

    from rest_framework import permissions
    class IsOwnerOrReadOnly(permissions.BasePermission):

# 重写has_object_permission方法,自定义权限类
def has_object_permission(self, request, view, obj):
    # Read permissions are allowed to any request,
    # so we'll always allow GET, HEAD or OPTIONS requests.
    if request.method in permissions.SAFE_METHODS:
        return True

    # Instance must have an attribute named `owner`.
    #obj相当于数据库中的model,这里要把owner改为我们数据库中的user
    return obj.user == request.user
局部使用
    from .permiss import IsOwnerOrReadOnly
    from rest_framework.mixins import CreateModelMixin, 
    from rest_framework.viewsets import GenericViewSet

  class Run(CreateModelMixin,GenericViewSet):
permission_classes= [IsOwnerOrReadOnly]  #自定义认证类局部使用
全局使用权限认证
    REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES':['store.utils.permisss.IsOwnerOrReadOnly']

}

节流

自定义节流类
    VISIT_RECORD = {}
class VisitThrottle(object):

    def __init__(self):
        self.history = None

    def allow_request(self,request,view):
        #实现节流的逻辑
        #基于ip做节流
        # #获取用户访问的IP地址
        # ip_address = request._request.META.get('REMOTE_ADDR')
        ctime = time.time()
        # if ip_address not in VISIT_RECORD:
        #     #第一次访问的时候将访问的时间存储在字典中(ip地址为Key,访问的时间为value值)
        #     VISIT_RECORD[ip_address] = [ctime,]
        #
        # #第二次访问的时候取出访问的历史记录
        # history = VISIT_RECORD[ip_address]

        # 基于用户的节流
        username = request.user.username
        if username not in VISIT_RECORD:
            VISIT_RECORD[username] = [ctime, ]
        history = VISIT_RECORD[username]
        self.history = history

        while history and history[-1] < ctime - 10:
            #如果访问的时间记录超过60秒,就把超过60秒的时间记录移除
            history.pop()

        if len(history) < 6:
            history.insert(0,ctime)
            return True

        return False

    def wait(self):
        #一旦用户访问次数到达阀值,显示用户需要等待的时间
        ctime = time.time()
                    #09:54:30    09:54:28
        return 10 - (ctime - self.history[-1])
局部使用
    class OrderView(APIView):
            # throttle_classes设置节流类
            throttle_classes = [VisitThrottle,]
全局设置
        REST_FRAMEWORK = {
   'DEFAULT_THROTTLE_CLASSES':['unitls.throttle.VisitThrottle'],
}  

使用DRF内置的限频类

from rest_framework.throttling import  SimpleRateThrottle

推荐使用这种

class VisitThrottle(SimpleRateThrottle):
  #没有登录用户,每分钟访问10次
  scope = 'unlogin'
  def get_cache_key(self, request, view):
  return request.user.username

全局设置

    REST_FRAMEWORK = {
   'DEFAULT_THROTTLE_RATES':{
       'unlogin':'10/m',
       'logined':'3/m',
   },
   'DEFAULT_THROTTLE_CLASSES':['unitls.throttle.VisitThrottle'],

}
不想限流 可将列表设为空 throttle_classes = []

版本控制

    自定义版本控制类

class ParmasVersion(object):
    def determine_version(self, request, *args, **kwargs):
        version = request.query_params.get('version')
        return version


使用(局部)

class VersionView(APIView):
    #设置获取版本的类
    versioning_class = ParmasVersion


全局设置

 'DEFAULT_VERSIONING_CLASS':'unitls.version.ParmasVersion',


使用 DRF内置的版本控制类QueryParameterVersioning(局部)

from rest_framework.versioning import QueryParameterVersioning
class VersionView(APIView):
    #设置获取版本的类
    versioning_class = QueryParameterVersioning


设置文件中的配置信息

REST_FRAMEWORK = {
    'VERSION_PARAM':'version',
    'DEFAULT_VERSION':'v1',
    'ALLOWED_VERSIONS':['v1','v2'],
}


全局设置

REST_FRAMEWORK = {
    'VERSION_PARAM':'version',
    'DEFAULT_VERSION':'v1',
    'ALLOWED_VERSIONS':['v1','v2'],
    'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.QueryParameterVersioning',
}



使用 DRF内置的版本控制类URLPathVersioning(局部)

from rest_framework.versioning import URLPathVersioning
class VersionView(APIView):
    #设置获取版本的类
    versioning_class = URLPathVersioning


设置文件中的配置信息

REST_FRAMEWORK = {
    'VERSION_PARAM':'version',
    'DEFAULT_VERSION':'v1',
    'ALLOWED_VERSIONS':['v1','v2'],
}


全局设置

REST_FRAMEWORK = {
    'VERSION_PARAM':'version',
    'DEFAULT_VERSION':'v1',
    'ALLOWED_VERSIONS':['v1','v2'],
    'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning',
}


如果使用URLPathVersioning,路由格式如下

url(r"^(?P<version>[v1|v2]+)/version/",VersionView.as_view(),name='vvvv')


#使用 DRF内置的版本控制类URLPathVersioning 反向生成url地址

#反向生成url地址 reverse
obj = request.versioning_scheme
url1 = obj.reverse(viewname='orders',request=request)

#使用django的reverse方法反响生成url地址
from django.urls import reverse
url2 = reverse(viewname='orders',kwargs={'version':'v2'})

解析器

因为开发人员post请求上传数据时,传递的数据类型不同,我们可能在request._request.POST中获取不到数据

    case1: Content-Type : application/x-www-form-urlencoded
服务端接收到的post请求的数据格式:username=xxxxx&age=18&sex=男
我们就可以在request._request.POST中获取到数据

class UserInfoView(APIView):
    def post(self,request,*args,**kwargs):
        username = request._request.POST.get('username')
        age = request._request.POST.get('age')
        sex = request._request.POST.get('sex')


case2:Content-Type:application/json
服务端接收到的post请求的数据格式就是json数据:{"username":"xxxx","age":"18","sex":"男"}
在request._request.POST中就获取不到数据,但是在request.body中可以拿到

class UserInfoView(APIView):
    def post(self,request,*args,**kwargs):
        import json
        data = json.loads(request.body.decode('utf8'))
        print(data)


DRF内置的解析器FormParser,JSONParser
使用(局部):

   from rest_framework.parsers import FormParser,JSONParser
   class UserInfoView(APIView):
      parser_classes = [FormParser,JSONParser]
    
    #这时DRF 内部代码会根据request.Content-Type和解析器支持的media_type比较
    从而选择对应的解析器
    
    def post(self,request,*args,**kwargs):
        # 如果使用JSONParser、FormParser解析数据的话
        data = request.data
        print(data)

序列化

    Django的序列化

#django序例化方式一
books = models.BookInfo.objects.all().values('id','bookname')
books = list(books)
print(type(books), books)
self.ret['books'] = books

#django序例化方式二
books = models.BookInfo.objects.all()
books = [model_to_dict(item) for item in books]
self.ret['books'] = books


DRF 序列化
 第一种:继承自serializers.Serializer

 class BookDetailSerializer(serializers.Serializer):
         # 正常的字段序列化
         id = serializers.IntegerField()
         bookname = serializers.CharField()
         author = serializers.CharField()
         category = serializers.IntegerField()
         bookdesc = serializers.CharField()
         
         
         # 获取枚举类型的文本是 source=get_字段名_display
         status = serializers.CharField(
             source='get_status_display'
         )
         categoryname = serializers.CharField(
             source='get_category_display'
         )
         
         # 自定义方法获取字段
         chpaters = serializers.SerializerMethodField()
         #序列化时可以自定义方法获取字段
         def get_chpaters(self,row):
             """ row - > bookinfo """
                 chpaters = models.ChpaterInfo.objects.filter(book=row)
                 ser = ChpaterSerializer(instance=chpaters,many=True,
                                         context=self.context
                                         )
                 return ser.data

 序列化时生成url

url = serializers.HyperlinkedIdentityField(
view_name='chpaterdetail', lookup_field='id',
lookup_url_kwarg='pk',
)

注意:如果序列化类中使用HyperlinkedIdentityField生成url,那我们在序例化时添加context={'request': request}

ser = BookDetailSerializer(
instance=obj,many=False,
context={'request': request}
)


如果出现关联关系时,获取model对像的某一个字段

bookname = serializers.CharField(source='book.bookname')
第二种继承自serializers.ModelSerializer
    class ChpaterDetailSerializer(serializers.ModelSerializer):
#使用ModelSerializer进行章节详情的序列化
bookname = serializers.CharField(source='book.bookname')
class Meta:
    model = models.ChpaterInfo
    #fields = "__all__"
    fields = ['id','bookname']


DRF (序列化时)自定义方法获取数据

 book = serializers.SerializerMethodField()

 def get_book(self,row):
     """ row - > UserInfo"""
         print('======',row.book.all())
         ser = UsersBooksSerializer(
             instance=row.book.all(),
             many=True
         )
    
         return ser.data


DRF depth深度的使用
# depth会根据关联的数据不停的深入将数据获取出来(最多不超过10层)
# depth = 1

class UsersSerializer(serializers.ModelSerializer):
class Meta:
    model = models.UserInfo
    fields = "__all__"
    #depth会根据关联的数据不停的深入将数据获取出来(最多不超过10层)
    depth = 1


DRF序列化的验证功能

class UsersSerializer(serializers.ModelSerializer):
#自定义验证错误的信息
username = serializers.CharField(error_messages={'required':'用户名不能为空'})
class Meta:
    model = models.UserInfo
    fields = "__all__"


class UsersView(APIView):
    def post(self,request,*args,**kwargs):
      """DRF 序列化自带验证功能"""
        data = request.data
    #print(data)
        ser = UsersSerializer(data=data)
        if ser.is_valid(): # ser.is_valid()y验证数据的有效性
            print('验证后的数据',ser.validated_data)
        #验证后的数据正确后,保存数据至数据库
          ser.save()
        else:
            #上传数据不符合规范时ser.errors,返回错误详细
            print(ser.errors)
        return Response(data)

自定义字段验证规则

class UsersInfoSerializer(serializers.ModelSerializer):
username = serializers.CharField(error_messages={'required':'用户名不能为空'})
    class Meta:
        model = models.UserInfo
        fields = "__all__"
    
    # 用户名中必须包含老王两个字,不包含则认为名字无效
    def validate_username(self,validated_value):
        print(validated_value)
        from rest_framework.exceptions import ValidationError
        if '老王' not in validated_value:
        #验证不通过,抛出异常
            raise ValidationError('用户名不合法')
        #验证通过,返回数据
        return validated_value

分页

    自定义分页类PageNumberPagination
  # 自定制分页类
class MyPageNumberPagination(PageNumberPagination):
"""[http://127.0.0.1:8000/api/userpage/?    page=1&pagesize=10](https://links.jianshu.com/go?to=http%3A%2F%2F127.0.0.1%3A8000%2Fapi%2Fuserpage%2F%3Fpage%3D1%26pagesize%3D10)"""
# page_size每一返回多少条
page_size = 5
# 设置分页的参数名
page_query_param = 'page'
# 设置每页返回数据量的参数名
page_size_query_param = 'pagesize'
# 设置每页最大返回的条数
max_page_size = 6

使用分页

          class UsersPageView(APIView):
      
      def get(self,request,*args,**kwargs):
          # 获取表中所有用户的row(记录)
          obj = models.UserInfo.objects.all()
          #实例化分页的类
          #page_obj = PageNumberPagination()
          page_obj = MyPageNumberPagination()
          #获取分页数据
          page_data = page_obj.paginate_queryset( queryset=obj,request=request,view=self)
          # 序列化
          ser = UsersSerializer(instance=page_data,many=True)

          # return Response(ser.data)
          #get_paginated_response会返回上一页下一页和总条数
          return page_obj.get_paginated_response(ser.data)

自定义分页类LimitOffsetPagination
from  rest_framework.pagination import LimitOffsetPagination

class MyLimitOffsetPagination(LimitOffsetPagination):
    """http://127.0.0.1:8000/api/userpage/?limit=10&offset=0"""
    default_limit = 5
    limit_query_param = 'limit'
    offset_query_param = 'offset'
    max_limit = 7


自定义分页类CursorPagination(会对分页参数进行加密)
from  rest_framework.pagination import CursorPagination

class MyCursorPagination(CursorPagination):
    """http://127.0.0.1:8000/api/userpage/?cursor=cD01"""
    cursor_query_param = 'cursor'
    page_size = 4
    #返回数据市的排序的方式
    ordering = '-id'
    max_page_size = 8

 设置全局的分页
 """
     REST_FRAMEWORK = {
         'DEFAULT_PAGINATION_CLASS':'unitl.pagination.MyCursorPagination',
         'PAGE_SIZE':3
     }
 """

视图

路由

     #自动路由配置

 from django.conf.urls import url,include
 from api import views
 from rest_framework import routers
 
 router = routers.DefaultRouter()
 router.register(r"bookpage",views.BookView,base_name='bookpage')
 
 
 urlpatterns = [
    url(r'v1/',include(router.urls)),
 ]

 
自动路由会生成四个接口
^api/ v1/ ^bookpage/$ [name='bookpage-list']
^api/ v1/ ^bookpage\.(?P<format>[a-z0-9]+)/?$ [name='bookpage-list']
^api/ v1/ ^bookpage/(?P<pk>[^/.]+)/$ [name='bookpage-detail']
^api/ v1/ ^bookpage/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='bookpage-detail']

渲染器

    INSTALLED_APPS = [
              'rest_framework',
             ]

from rest_framework.renderers import BrowsableAPIRenderer,JSONRenderer,AdminRenderer

class BookView(ModelViewSet):
    # 设置渲染器类型
    renderer_classes = [JSONRenderer]
上一篇下一篇

猜你喜欢

热点阅读