jumpserver/apps/common/api/serializer.py

51 lines
1.7 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
#
from rest_framework.request import Request
2021-10-21 08:39:52 +00:00
__all__ = ['SerializerMixin']
class SerializerMixin:
""" 根据用户请求动作的不同,获取不同的 `serializer_class `"""
action: str
request: Request
serializer_classes = None
single_actions = ['put', 'retrieve', 'patch']
2022-04-06 03:29:16 +00:00
def get_serializer_classes(self):
2022-05-04 01:57:45 +00:00
classes = getattr(self, 'serializer_classes', None) or {}
return dict(classes)
2022-04-06 03:29:16 +00:00
def get_serializer_class_by_view_action(self):
2022-04-06 03:29:16 +00:00
serializer_classes = self.get_serializer_classes()
if serializer_classes is None:
return None
2022-05-04 01:57:45 +00:00
if not isinstance(serializer_classes, dict):
return None
2022-05-04 01:57:45 +00:00
serializer_classes = dict(serializer_classes)
view_action = self.request.query_params.get('action') or self.action or 'list'
if self.request.query_params.get('format'):
view_action = 'retrieve'
2022-05-04 01:57:45 +00:00
serializer_class = serializer_classes.get(view_action)
if serializer_class is None:
view_method = self.request.method.lower()
2022-05-04 01:57:45 +00:00
serializer_class = serializer_classes.get(view_method)
if serializer_class is None and view_action in self.single_actions:
2022-05-04 01:57:45 +00:00
serializer_class = serializer_classes.get('single')
if serializer_class is None:
2022-05-04 01:57:45 +00:00
serializer_class = serializer_classes.get('display')
if serializer_class is None:
2022-05-04 01:57:45 +00:00
serializer_class = serializer_classes.get('default')
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