mirror of
https://github.com/jumpserver/jumpserver.git
synced 2025-09-05 01:11:57 +00:00
[Feature] 权限管理-> 远程应用 添加 api (#4040)
* [Feature] 权限管理-> 远程应用 添加 api * [Feature] 添加 RelationMixin
This commit is contained in:
@@ -3,7 +3,9 @@
|
||||
import time
|
||||
from hashlib import md5
|
||||
from threading import Thread
|
||||
from collections import defaultdict
|
||||
|
||||
from django.db.models.signals import m2m_changed
|
||||
from django.core.cache import cache
|
||||
from django.http import JsonResponse
|
||||
from rest_framework.response import Response
|
||||
@@ -14,7 +16,7 @@ from ..utils import lazyproperty
|
||||
|
||||
__all__ = [
|
||||
"JSONResponseMixin", "CommonApiMixin",
|
||||
'AsyncApiMixin',
|
||||
'AsyncApiMixin', 'RelationMixin'
|
||||
]
|
||||
|
||||
|
||||
@@ -187,3 +189,47 @@ class AsyncApiMixin(InterceptMixin):
|
||||
data["error"] = str(e)
|
||||
data["status"] = "error"
|
||||
cache.set(key, data, 600)
|
||||
|
||||
|
||||
class RelationMixin:
|
||||
m2m_field = None
|
||||
from_field = None
|
||||
to_field = None
|
||||
to_model = None
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
assert self.m2m_field is not None, '''
|
||||
`m2m_field` should not be `None`
|
||||
'''
|
||||
|
||||
self.from_field = self.m2m_field.m2m_field_name()
|
||||
self.to_field = self.m2m_field.m2m_reverse_field_name()
|
||||
self.to_model = self.m2m_field.related_model
|
||||
self.through = getattr(self.m2m_field.model, self.m2m_field.attname).through
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = self.through.objects.all()
|
||||
return queryset
|
||||
|
||||
def send_post_add_signal(self, instances):
|
||||
if not isinstance(instances, list):
|
||||
instances = [instances]
|
||||
|
||||
from_to_mapper = defaultdict(list)
|
||||
|
||||
for i in instances:
|
||||
to_id = getattr(i, self.to_field).id
|
||||
from_obj = getattr(i, self.from_field)
|
||||
from_to_mapper[from_obj].append(to_id)
|
||||
|
||||
for from_obj, to_ids in from_to_mapper.items():
|
||||
m2m_changed.send(
|
||||
sender=self.through, instance=from_obj, action='post_add',
|
||||
reverse=False, model=self.to_model, pk_set=to_ids
|
||||
)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
instance = serializer.save()
|
||||
self.send_post_add_signal(instance)
|
||||
|
Reference in New Issue
Block a user