Django Rest Permission

API Permission

示例代码1:CRUD权限

创建API权限管理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class 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 False

class 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使用权限管理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ProjectViewSet(CreateProjectMixin,
RetrieveProjectMixin,
UpdateProjectMixin,
DestroyProjectMixin,
ProjectListPermission,
BaseModelApi)):
permission_classes = [IsAuthenticated, ProjectAPIPerm]
serializer_class = ProjectWithAttrSerializer

def get_class(self):
"""
返回Class对象
:return:
"""
return Project