Browse Source

perf: serializer (#9034)

Co-authored-by: feng <1304903146@qq.com>
pull/9035/head
fit2bot 2 years ago committed by GitHub
parent
commit
a5cef74356
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      apps/assets/serializers/account/account.py
  2. 15
      apps/assets/serializers/account/backup.py
  3. 41
      apps/assets/serializers/account/base.py
  4. 40
      apps/assets/serializers/automations/change_secret.py
  5. 8
      apps/assets/serializers/base.py
  6. 6
      apps/assets/serializers/gathered_user.py
  7. 15
      apps/tickets/serializers/flow.py

1
apps/assets/serializers/account/account.py

@ -58,7 +58,6 @@ class AccountSerializer(AccountSerializerCreateMixin, BaseAccountSerializer):
required=False, queryset=Asset.objects,
label=_('Asset'), attrs=('id', 'name', 'address', 'platform_id')
)
secret_type = LabeledChoiceField(choices=SecretType.choices, label=_('Secret type'))
class Meta(BaseAccountSerializer.Meta):
model = Account

15
apps/assets/serializers/account/backup.py

@ -6,6 +6,8 @@ from rest_framework import serializers
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from ops.mixin import PeriodTaskSerializerMixin
from common.utils import get_logger
from common.const.choices import Trigger
from common.drf.fields import LabeledChoiceField
from assets.models import AccountBackupPlan, AccountBackupPlanExecution
@ -32,17 +34,12 @@ class AccountBackupPlanSerializer(PeriodTaskSerializerMixin, BulkOrgResourceMode
class AccountBackupPlanExecutionSerializer(serializers.ModelSerializer):
trigger_display = serializers.ReadOnlyField(
source='get_trigger_display', label=_('Trigger mode')
)
trigger = LabeledChoiceField(choices=Trigger.choices, label=_('Trigger mode'))
class Meta:
model = AccountBackupPlanExecution
fields = [
'id', 'date_start', 'timedelta', 'plan_snapshot', 'trigger', 'reason',
'is_success', 'plan', 'org_id', 'recipients', 'trigger_display'
]
read_only_fields = (
read_only_fields = [
'id', 'date_start', 'timedelta', 'plan_snapshot', 'trigger', 'reason',
'is_success', 'org_id', 'recipients'
)
]
fields = read_only_fields + ['plan']

41
apps/assets/serializers/account/base.py

@ -1,28 +1,19 @@
# -*- coding: utf-8 -*-
from io import StringIO
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from common.utils import validate_ssh_private_key, ssh_private_key_gen
from common.drf.fields import EncryptedField
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from assets.models import BaseAccount
from assets.serializers.base import AuthValidateMixin
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
__all__ = ['BaseAccountSerializer']
class BaseAccountSerializer(BulkOrgResourceModelSerializer):
secret = EncryptedField(
label=_('Secret'), required=False, allow_blank=True,
allow_null=True, max_length=40960
)
class BaseAccountSerializer(AuthValidateMixin, BulkOrgResourceModelSerializer):
class Meta:
model = BaseAccount
fields_mini = ['id', 'name', 'username']
fields_small = fields_mini + [
'secret_type', 'secret', 'has_secret',
'secret_type', 'secret', 'has_secret', 'passphrase',
'privileged', 'is_active', 'specific',
]
fields_other = ['created_by', 'date_created', 'date_updated', 'comment']
@ -32,29 +23,5 @@ class BaseAccountSerializer(BulkOrgResourceModelSerializer):
'date_verified', 'created_by', 'date_created',
]
extra_kwargs = {
'secret': {'write_only': True},
'passphrase': {'write_only': True},
'specific': {'label': _('Specific')},
}
def validate_private_key(self, private_key):
if not private_key:
return ''
passphrase = self.initial_data.get('passphrase')
passphrase = passphrase if passphrase else None
valid = validate_ssh_private_key(private_key, password=passphrase)
if not valid:
raise serializers.ValidationError(_("private key invalid or passphrase error"))
private_key = ssh_private_key_gen(private_key, password=passphrase)
string_io = StringIO()
private_key.write_private_key(string_io)
private_key = string_io.getvalue()
return private_key
def validate_secret(self, value):
secret_type = self.initial_data.get('secret_type')
if secret_type == 'ssh_key':
value = self.validate_private_key(value)
return value

40
apps/assets/serializers/automations/change_secret.py

@ -3,10 +3,11 @@
from django.utils.translation import ugettext as _
from rest_framework import serializers
from assets.serializers.base import AuthValidateMixin
from assets.models import ChangeSecretAutomation, ChangeSecretRecord
from assets.const import DEFAULT_PASSWORD_RULES, SecretType, SecretStrategy
from common.utils import get_logger
from common.drf.fields import LabeledChoiceField, ObjectRelatedField
from assets.serializers.base import AuthValidateMixin
from assets.const import DEFAULT_PASSWORD_RULES, SecretType, SecretStrategy, SSHKeyStrategy
from assets.models import Asset, Account, ChangeSecretAutomation, ChangeSecretRecord, AutomationExecution
from .base import BaseAutomationSerializer
@ -20,19 +21,17 @@ __all__ = [
class ChangeSecretAutomationSerializer(AuthValidateMixin, BaseAutomationSerializer):
password_rules = serializers.DictField(default=DEFAULT_PASSWORD_RULES)
secret_strategy_display = serializers.ReadOnlyField(
source='get_secret_strategy_display', label=_('Secret strategy')
secret_strategy = LabeledChoiceField(
choices=SecretStrategy.choices, required=True, label=_('Secret strategy')
)
ssh_key_change_strategy_display = serializers.ReadOnlyField(
source='get_ssh_key_strategy_display', label=_('SSH Key strategy')
ssh_key_change_strategy = LabeledChoiceField(
choices=SSHKeyStrategy.choices, required=False, label=_('SSH Key strategy')
)
password_rules = serializers.DictField(default=DEFAULT_PASSWORD_RULES)
class Meta:
model = ChangeSecretAutomation
read_only_fields = BaseAutomationSerializer.Meta.read_only_fields + [
'secret_strategy_display', 'ssh_key_change_strategy_display'
]
read_only_fields = BaseAutomationSerializer.Meta.read_only_fields
fields = BaseAutomationSerializer.Meta.fields + read_only_fields + [
'secret_type', 'secret_strategy', 'secret', 'password_rules',
'ssh_key_change_strategy', 'passphrase', 'recipients',
@ -84,26 +83,21 @@ class ChangeSecretAutomationSerializer(AuthValidateMixin, BaseAutomationSerializ
class ChangeSecretRecordSerializer(serializers.ModelSerializer):
asset_display = serializers.SerializerMethodField(label=_('Asset display'))
account_display = serializers.SerializerMethodField(label=_('Account display'))
is_success = serializers.SerializerMethodField(label=_('Is success'))
asset = ObjectRelatedField(queryset=Asset.objects, label=_('Asset'))
account = ObjectRelatedField(queryset=Account.objects, label=_('Account'))
execution = ObjectRelatedField(
queryset=AutomationExecution.objects, label=_('Automation task execution')
)
class Meta:
model = ChangeSecretRecord
fields = [
'id', 'asset', 'account', 'date_started', 'date_finished',
'is_success', 'error', 'execution', 'asset_display', 'account_display'
'id', 'asset', 'account', 'date_started',
'date_finished', 'is_success', 'error', 'execution',
]
read_only_fields = fields
@staticmethod
def get_asset_display(instance):
return str(instance.asset)
@staticmethod
def get_account_display(instance):
return str(instance.account)
@staticmethod
def get_is_success(obj):
if obj.status == 'success':

8
apps/assets/serializers/base.py

@ -3,15 +3,17 @@
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from common.drf.fields import EncryptedField
from assets.const import SecretType
from common.drf.fields import EncryptedField, LabeledChoiceField
from .utils import validate_password_for_ansible, validate_ssh_key
class AuthValidateMixin(serializers.Serializer):
secret_type = serializers.CharField(label=_('Secret type'), max_length=16, required=True)
secret_type = LabeledChoiceField(
choices=SecretType.choices, required=True, label=_('Secret type')
)
secret = EncryptedField(
label=_('Secret'), required=False, max_length=16384, allow_blank=True,
label=_('Secret'), required=False, max_length=40960, allow_blank=True,
allow_null=True, write_only=True,
)
passphrase = serializers.CharField(

6
apps/assets/serializers/gathered_user.py

@ -1,13 +1,15 @@
# -*- coding: utf-8 -*-
#
from django.utils.translation import ugettext_lazy as _
from orgs.mixins.serializers import OrgResourceModelSerializerMixin
from ..models import GatheredUser
from common.drf.fields import ObjectRelatedField
from ..models import GatheredUser, Asset
class GatheredUserSerializer(OrgResourceModelSerializerMixin):
asset = ObjectRelatedField(queryset=Asset.objects, label=_('Asset'))
class Meta:
model = GatheredUser
fields_mini = ['id']

15
apps/tickets/serializers/flow.py

@ -5,21 +5,24 @@ from rest_framework import serializers
from orgs.models import Organization
from orgs.utils import get_current_org_id
from orgs.mixins.serializers import OrgResourceModelSerializerMixin
from common.drf.fields import LabeledChoiceField
from tickets.models import TicketFlow, ApprovalRule
from tickets.const import TicketApprovalStrategy
from tickets.const import TicketApprovalStrategy, TicketType
__all__ = ['TicketFlowSerializer']
class TicketFlowApproveSerializer(serializers.ModelSerializer):
strategy_display = serializers.ReadOnlyField(source='get_strategy_display', label=_('Approve strategy'))
strategy = LabeledChoiceField(
choices=TicketApprovalStrategy.choices, required=True, label=_('Approve strategy')
)
assignees_read_only = serializers.SerializerMethodField(label=_('Assignees'))
assignees_display = serializers.SerializerMethodField(label=_('Assignees display'))
class Meta:
model = ApprovalRule
fields_small = [
'level', 'strategy', 'assignees_read_only', 'assignees_display', 'strategy_display'
'level', 'strategy', 'assignees_read_only', 'assignees_display',
]
fields_m2m = ['assignees', ]
fields = fields_small + fields_m2m
@ -46,14 +49,16 @@ class TicketFlowApproveSerializer(serializers.ModelSerializer):
class TicketFlowSerializer(OrgResourceModelSerializerMixin):
type_display = serializers.ReadOnlyField(source='get_type_display', label=_('Type display'))
type = LabeledChoiceField(
choices=TicketType.choices, required=True, label=_('Type')
)
rules = TicketFlowApproveSerializer(many=True, required=True)
class Meta:
model = TicketFlow
fields_mini = ['id', ]
fields_small = fields_mini + [
'type', 'type_display', 'approval_level', 'created_by', 'date_created', 'date_updated',
'type', 'approval_level', 'created_by', 'date_created', 'date_updated',
'org_id', 'org_name'
]
fields = fields_small + ['rules', ]

Loading…
Cancel
Save