Skip to content

Commit

Permalink
fix: 修改序列化问题 TencentBlueKing#7626
Browse files Browse the repository at this point in the history
  • Loading branch information
guohelu committed Dec 12, 2024
1 parent 48aa0d9 commit 964f072
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 50 deletions.
11 changes: 6 additions & 5 deletions gcloud/contrib/template_market/permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,13 @@ def has_permission(self, request, view):

class SharedProcessTemplatePermission(permissions.BasePermission):
def has_permission(self, request, view):
username = request.user.username
serializer = view.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)

template_id_list = [template.get("id") for template in serializer.validated_data["templates"]]
if view.action in ["create", "partial_update"]:
username = request.user.username
serializer = view.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)

template_id_list = serializer.validated_data["templates"]

iam_multi_resource_auth_or_raise(
username, IAMMeta.FLOW_EDIT_ACTION, template_id_list, "resources_list_for_flows"
)
Expand Down
42 changes: 11 additions & 31 deletions gcloud/contrib/template_market/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
specific language governing permissions and limitations under the License.
"""
import json
import logging
from rest_framework import serializers

from gcloud.constants import DATETIME_FORMAT
Expand All @@ -34,11 +33,10 @@ class TemplateProjectBaseSerializer(serializers.Serializer):
class TemplateSharedRecordSerializer(serializers.ModelSerializer):
project_id = serializers.CharField(required=True, max_length=32, help_text="项目id")
templates = serializers.ListField(required=True, help_text="关联的模板列表")
creator = serializers.CharField(required=False, max_length=32, help_text="创建者")
creator = serializers.CharField(required=True, max_length=32, help_text="创建者")
create_at = serializers.DateTimeField(required=False, help_text="创建时间", format=DATETIME_FORMAT)
update_at = serializers.DateTimeField(required=False, help_text="更新时间", format=DATETIME_FORMAT)
extra_info = serializers.JSONField(required=False, allow_null=True, help_text="额外信息")
id = serializers.IntegerField(required=False, help_text="共享实例id")
name = serializers.CharField(required=True, help_text="共享名称")
code = serializers.CharField(required=True, help_text="共享标识")
category = serializers.CharField(required=True, help_text="共享分类")
Expand All @@ -56,41 +54,23 @@ class Meta:
"create_at",
"update_at",
"extra_info",
"labels",
"usage_content",
"id",
"name",
"code",
"category",
"risk_level",
"usage_id",
"labels",
"usage_content",
]

def convert_templates(self, templates):
return [template.get("id") for template in templates]

def create(self, validated_data):
try:
validated_data["templates"] = self.convert_templates(validated_data["templates"])
return TemplateSharedRecord.objects.create(
scene_shared_id=validated_data["id"],
project_id=validated_data["project_id"],
templates=validated_data["templates"],
creator=validated_data["creator"],
extra_info=validated_data["extra_info"],
)
except Exception:
logging.exception("Failed to create model sharing record")
raise Exception("Failed to create model sharing record")
fields_to_remove = ["name", "code", "category", "risk_level", "usage_id", "labels", "usage_content"]
for field in fields_to_remove:
validated_data.pop(field, None)
return super().create(validated_data)

def update(self, instance, validated_data):
try:
validated_data["templates"] = self.convert_templates(validated_data["templates"])
instance.project_id = validated_data["project_id"]
instance.templates = validated_data["templates"]
instance.creator = validated_data["creator"]
instance.extra_info = validated_data["extra_info"]
instance.save()
except Exception:
logging.exception("Failed to update model sharing record")
raise Exception("Failed to update model sharing record")
fields_to_remove = ["name", "code", "category", "risk_level", "usage_id", "labels", "usage_content"]
for field in fields_to_remove:
validated_data.pop(field, None)
return super().update(instance, validated_data)
26 changes: 12 additions & 14 deletions gcloud/contrib/template_market/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ def __init__(self, **kwargs):
super().__init__(**kwargs)
self.market_client = MarketAPIClient()

def _build_template_data(self, serializer):

def _build_template_data(self, serializer, **kwargs):
templates = TaskTemplate.objects.filter(id__in=serializer.validated_data["templates"], is_deleted=False)
template_id_list = [{"id": template.id, "name": template.name} for template in templates]
data = {
"name": serializer.validated_data["name"],
"code": serializer.validated_data["code"],
Expand All @@ -69,17 +70,15 @@ def _build_template_data(self, serializer):
"labels": serializer.validated_data["labels"],
"source_system": "bk_sops",
"project_code": serializer.validated_data["project_id"],
"templates": json.dumps(serializer.validated_data["templates"]),
"templates": json.dumps(template_id_list),
"usage_content": serializer.validated_data["usage_content"],
}
scene_shared_id = serializer.validated_data.get("id")
scene_shared_id = kwargs.get("scene_shared_id")
if scene_shared_id:
data["id"] = scene_shared_id
return data

def _get_processes_count(self, templates):
template_id_list = [template.get("id") for template in templates]

def _get_processes_count(self, template_id_list):
template_objs = TaskTemplate.objects.filter(id__in=template_id_list)

total_count = 0
Expand Down Expand Up @@ -126,8 +125,8 @@ def create(self, request, *args, **kwargs):
"code": err_code.OPERATION_FAIL.code,
}
)
serializer.validated_data["id"] = response_data["data"]["id"]
serializer.create(serializer.validated_data)
serializer.validated_data["scene_shared_id"] = response_data["data"]["id"]
serializer.save()
return Response(
{
"result": True,
Expand All @@ -142,12 +141,12 @@ def create(self, request, *args, **kwargs):

@swagger_auto_schema(request_body=TemplateSharedRecordSerializer)
def partial_update(self, request, *args, **kwargs):
scene_shared_id = kwargs["pk"]
instance = self.queryset.get(scene_shared_id=scene_shared_id)
serializer = self.serializer_class(data=request.data, partial=True)
serializer.is_valid(raise_exception=True)

scene_shared_id = serializer.validated_data.get("id")

data = self._build_template_data(serializer)
data = self._build_template_data(serializer, scene_shared_id=scene_shared_id)
try:
response_data = self.market_client.patch_template(data, scene_shared_id)
if not response_data.get("result"):
Expand All @@ -158,8 +157,7 @@ def partial_update(self, request, *args, **kwargs):
"code": err_code.OPERATION_FAIL.code,
}
)
instance = self.queryset.get(scene_shared_id=scene_shared_id)
serializer.update(instance, serializer.validated_data)
serializer.update(instance, validated_data=serializer.validated_data)
return Response(
{
"result": True,
Expand Down

0 comments on commit 964f072

Please sign in to comment.