mirror of https://github.com/jumpserver/jumpserver
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.7 KiB
49 lines
1.7 KiB
3 years ago
|
# -*- coding: utf-8 -*-
|
||
|
#
|
||
|
|
||
|
from rest_framework.request import Request
|
||
|
|
||
3 years ago
|
__all__ = ['SerializerMixin']
|
||
3 years ago
|
|
||
|
|
||
|
class SerializerMixin:
|
||
|
""" 根据用户请求动作的不同,获取不同的 `serializer_class `"""
|
||
|
|
||
|
action: str
|
||
|
request: Request
|
||
|
|
||
|
serializer_classes = None
|
||
|
single_actions = ['put', 'retrieve', 'patch']
|
||
|
|
||
3 years ago
|
def get_serializer_classes(self):
|
||
3 years ago
|
classes = getattr(self, 'serializer_classes', None) or {}
|
||
|
return dict(classes)
|
||
3 years ago
|
|
||
3 years ago
|
def get_serializer_class_by_view_action(self):
|
||
3 years ago
|
serializer_classes = self.get_serializer_classes()
|
||
|
if serializer_classes is None:
|
||
3 years ago
|
return None
|
||
3 years ago
|
if not isinstance(serializer_classes, dict):
|
||
3 years ago
|
return None
|
||
3 years ago
|
serializer_classes = dict(serializer_classes)
|
||
3 years ago
|
view_action = self.request.query_params.get('action') or self.action or 'list'
|
||
3 years ago
|
serializer_class = serializer_classes.get(view_action)
|
||
3 years ago
|
|
||
|
if serializer_class is None:
|
||
|
view_method = self.request.method.lower()
|
||
3 years ago
|
serializer_class = serializer_classes.get(view_method)
|
||
3 years ago
|
|
||
|
if serializer_class is None and view_action in self.single_actions:
|
||
3 years ago
|
serializer_class = serializer_classes.get('single')
|
||
3 years ago
|
if serializer_class is None:
|
||
3 years ago
|
serializer_class = serializer_classes.get('display')
|
||
3 years ago
|
if serializer_class is None:
|
||
3 years ago
|
serializer_class = serializer_classes.get('default')
|
||
3 years ago
|
return serializer_class
|
||
|
|
||
|
def get_serializer_class(self):
|
||
|
serializer_class = self.get_serializer_class_by_view_action()
|
||
|
if serializer_class is None:
|
||
|
serializer_class = super().get_serializer_class()
|
||
|
return serializer_class
|