[Feature] 权限管理-> 远程应用 添加 api (#4040)

* [Feature] 权限管理-> 远程应用 添加 api

* [Feature] 添加 RelationMixin
This commit is contained in:
xinwen
2020-05-28 17:00:42 +08:00
committed by GitHub
parent 3e5d949610
commit 7dde15cb04
19 changed files with 291 additions and 45 deletions

View File

@@ -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)