Django Rest Permission 发表于 2017-10-25 | 分类于 python , django , rest API Permission示例代码1:CRUD权限创建API权限管理类 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253class BasePerms(BasePermission): # API require permissions api_perms = [] @staticmethod def check_user_perms(user, perms): if user and perms and isinstance(perms, list): return user.has_perms(perms) return False @staticmethod def check_user_perm(user, codename): if user and codename: return user.has_perm(codename) return Falseclass BaseModelAPIPerms(BasePerms): def has_permission(self, request, view): # is_superuser 超级权限 if request.user.is_superuser: return True codename = self.get_codename(request, view) return self.check_user_perm(request.user, codename) @staticmethod def get_codename(request, view): req_method = request.method serializer_class = view.serializer_class codename = '' if serializer_class: meta = serializer_class.Meta if meta: model = meta.model if model: model_attr = getattr(model, '_meta') codename = "%s.{}_%s" % (getattr(model_attr, 'app_label', ''), getattr(model_attr, 'model_name', '')) if req_method == 'GET': return codename.format("access") elif req_method == 'POST': return codename.format("add") elif req_method == 'PUT': return codename.format("change") elif req_method == 'DELETE': return codename.format("delete") return codename API使用权限管理类 123456789101112131415class ProjectViewSet(CreateProjectMixin, RetrieveProjectMixin, UpdateProjectMixin, DestroyProjectMixin, ProjectListPermission, BaseModelApi)): permission_classes = [IsAuthenticated, ProjectAPIPerm] serializer_class = ProjectWithAttrSerializer def get_class(self): """ 返回Class对象 :return: """ return Project