Django rest-framework框架-用户权限实例

 

简单实例:

class MyPermission(object):
      '''
    权限控制类
   '''
      def has_permission(self,request,view):
          if request.user.user_type !=3:
              return False
          return True


class MyPermission1(object):
      '''
    权限控制类
   '''
message = "必须是SVPI才能访问!" def has_permission(self, request, view): if request.user.user_type == 3: return False return True ORDER_DICT = { 1:{ 'name': 'x', 'age': 18, 'gender':'y', 'content': '...' }, 2:{ 'name': 'z', 'age': 18, 'gender': 'h', 'content': '...' } } class OrderView(APIView): # 权限控制 按需添加 permission_classes = [MyPermission,] def get(self,request,*args,**kwargs): ret = {'code':1000,'msg':None,'data':None} try: ret['data'] = ORDER_DICT except Exception as e: pass return JsonResponse(ret) class UserInfoView(APIView): """ 订单相关业务(普通用户,VIP) """ # 权限控制 按需添加 permission_classes = [MyPermission1, ] def get(self,request,*args,**kwargs): return HttpResponse('用户信息')

  

如果没有配置:

permission_classes = [MyPermission,]

# 如果没有设置以上内容  默认源码会去 settings里面找
permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES

#全局设置
REST_FRAMEWORK = {
  "DEFAULT_PERMISSION_CLASSES": "api.utils.permission.Mypermission",
}

  

源码流程:

1--------
dispatch
2--------
initail
3--------
has_permission

  

改进版:

继承内置权限类:

from rest_framework.permissions import BasePermission
class MyPermission(BasePermission):
      '''
    权限控制类
   '''
      def has_permission(self,request,view):
          if request.user.user_type !=3:
              return False
          return True

  

1.必须继承 BasePermission类

2.必须实现has_permission方法

 

转载于:https://www.cnblogs.com/kuku0223/p/11340949.html

你可能感兴趣的:(Django rest-framework框架-用户权限实例)