@action【示例】
urls.py
from django.urls import path
from utils.ext_url import rbac_path
from utils.router import RbacSimpleRouter
from api import views
router = RbacSimpleRouter()
router.register(r"user", views.UserView, text="用户") # user-list user-detail
router.register(r"permission", views.PermissionView, text="权限") # permission-list get post
# /api/role/ role-list GET POST
# /api/role/permission role-total-permission GET
# /api/role/ID role-detail GET PUT DELETE
# /api/role/ID/permission role-permission GET
router.register(r"role", views.RoleView, text="角色") # role-list get post role-detail /api/role/id/
urlpatterns = [
path('login/', views.LoginView.as_view()),
]
urlpatterns += router.urls
views.py
from rest_framework.decorators import action
class RoleModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Role
fields = ["id", "name", ]
class RoleView(BaseView, ModelViewSet):
authentication_classes = [JwtAuthentication]
permission_classes = [RbacPermission]
queryset = models.Role.objects.all().order_by("-id")
serializer_class = RoleModelSerializer
@action(detail=False, methods=['get'], url_path="permission")
def total_permission(self, request):
# /api/role/permission/
info = {}
queryset = models.Permission.objects.all().order_by("route", "method")
for obj in queryset:
row = {"id": obj.id, "label": obj.method.upper()}
if obj.name not in info:
info[obj.name] = {
"label": obj.name,
"children": {
obj.route: {
"label": obj.route,
"node_horizontal": True,
"children": [
row
]
}
}
}
continue
if obj.route not in info[obj.name]['children']:
info[obj.name]['children'][obj.route] = {
"label": obj.route,
"node_horizontal": True,
"children": [
row
]
}
continue
info[obj.name]['children'][obj.route]['children'].append(row)
for item in info.values():
item['children'] = item['children'].values()
return Response(info.values())
@action(detail=True, methods=['get', "post"], url_path="permission")
def permission(self, request, pk):
if request.method == "GET":
# /api/role/pk=角色ID/ 获取pk用户关联的所有权限 [1,2,3]
queryset = models.Permission.objects.filter(role=pk)
per_id_list = {obj.id for obj in queryset}
return Response(per_id_list)
# 权限写入到数据库 [11,22,33,4]
per_id_list = request.data.get('permissions')
# print(per_id_list)
# instance = models.Role.objects.filter(id=pk).first()
# instance = models.Role.objects.get(id=pk)
instance = self.get_object()
instance.permissions.set(per_id_list)
return Response("OK")
注:
router.register(r'basic', basic.BasicView) # 它的name是通过basic前缀生成的 basic-list basic-detail
@action # 它的name是里面的方法名 permission-list