diff --git a/sysom_server/sysom_hotfix/apps/hotfix/migrations/0006_releasedhotfixlistmodule_serious_explain.py b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0006_releasedhotfixlistmodule_serious_explain.py new file mode 100644 index 0000000000000000000000000000000000000000..52b6c066b6beef28d75430732e37f97d7c82f7e3 --- /dev/null +++ b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0006_releasedhotfixlistmodule_serious_explain.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2.16 on 2023-12-18 02:07 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hotfix', '0005_releasedhotfixlistmodule'), + ] + + operations = [ + migrations.AddField( + model_name='releasedhotfixlistmodule', + name='serious_explain', + field=models.TextField(default='', verbose_name='推荐说明'), + ), + ] diff --git a/sysom_server/sysom_hotfix/apps/hotfix/migrations/0007_alter_releasedhotfixlistmodule_released_kernel_version.py b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0007_alter_releasedhotfixlistmodule_released_kernel_version.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d24ba413522e3f614589b696330a290ec3c5b7 --- /dev/null +++ b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0007_alter_releasedhotfixlistmodule_released_kernel_version.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2.16 on 2023-12-25 17:04 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hotfix', '0006_releasedhotfixlistmodule_serious_explain'), + ] + + operations = [ + migrations.AlterField( + model_name='releasedhotfixlistmodule', + name='released_kernel_version', + field=models.CharField(max_length=128, verbose_name='hotfix发布的内核版本'), + ), + ] diff --git a/sysom_server/sysom_hotfix/apps/hotfix/migrations/0008_alter_releasedhotfixlistmodule_released_kernel_version.py b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0008_alter_releasedhotfixlistmodule_released_kernel_version.py new file mode 100644 index 0000000000000000000000000000000000000000..15aaba8e44c36193c2778bd6f34ed400982d36cb --- /dev/null +++ b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0008_alter_releasedhotfixlistmodule_released_kernel_version.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2.16 on 2023-12-26 10:30 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hotfix', '0007_alter_releasedhotfixlistmodule_released_kernel_version'), + ] + + operations = [ + migrations.AlterField( + model_name='releasedhotfixlistmodule', + name='released_kernel_version', + field=models.CharField(max_length=180, verbose_name='hotfix发布的内核版本'), + ), + ] diff --git a/sysom_server/sysom_hotfix/apps/hotfix/migrations/0009_alter_releasedhotfixlistmodule_deprecated_info.py b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0009_alter_releasedhotfixlistmodule_deprecated_info.py new file mode 100644 index 0000000000000000000000000000000000000000..fd33eebfd5989e08bc37d37de1d88c74beebfb04 --- /dev/null +++ b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0009_alter_releasedhotfixlistmodule_deprecated_info.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2.16 on 2024-01-02 16:12 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hotfix', '0008_alter_releasedhotfixlistmodule_released_kernel_version'), + ] + + operations = [ + migrations.AlterField( + model_name='releasedhotfixlistmodule', + name='deprecated_info', + field=models.TextField(blank=True, default='', null=True, verbose_name='废弃原因或信息'), + ), + ] diff --git a/sysom_server/sysom_hotfix/apps/hotfix/migrations/0010_alter_releasedhotfixlistmodule_deprecated_info.py b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0010_alter_releasedhotfixlistmodule_deprecated_info.py new file mode 100644 index 0000000000000000000000000000000000000000..ae12e42e89133008b59681927a67366bebcb17d5 --- /dev/null +++ b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0010_alter_releasedhotfixlistmodule_deprecated_info.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2.16 on 2024-01-02 16:15 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hotfix', '0009_alter_releasedhotfixlistmodule_deprecated_info'), + ] + + operations = [ + migrations.AlterField( + model_name='releasedhotfixlistmodule', + name='deprecated_info', + field=models.TextField(blank=True, default='', verbose_name='废弃原因或信息'), + ), + ] diff --git a/sysom_server/sysom_hotfix/apps/hotfix/migrations/0011_auto_20240102_1820.py b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0011_auto_20240102_1820.py new file mode 100644 index 0000000000000000000000000000000000000000..440886c64fcd8f6d6b161b5b5ffb072b6164ca60 --- /dev/null +++ b/sysom_server/sysom_hotfix/apps/hotfix/migrations/0011_auto_20240102_1820.py @@ -0,0 +1,28 @@ +# Generated by Django 3.2.16 on 2024-01-02 18:20 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hotfix', '0010_alter_releasedhotfixlistmodule_deprecated_info'), + ] + + operations = [ + migrations.AlterField( + model_name='releasedhotfixlistmodule', + name='description', + field=models.TextField(blank=True, default='', verbose_name='hotfix问题描述'), + ), + migrations.AlterField( + model_name='releasedhotfixlistmodule', + name='download_link', + field=models.TextField(blank=True, default='', verbose_name='hotfix下载链接'), + ), + migrations.AlterField( + model_name='releasedhotfixlistmodule', + name='serious_explain', + field=models.TextField(blank=True, default='', verbose_name='推荐说明'), + ), + ] diff --git a/sysom_server/sysom_hotfix/apps/hotfix/models.py b/sysom_server/sysom_hotfix/apps/hotfix/models.py index 0119fa9b2e27f52bbe426ea00698716900831c17..6a03ca2d8c9b711acd4db93d8ea7bfb61dbe77fe 100644 --- a/sysom_server/sysom_hotfix/apps/hotfix/models.py +++ b/sysom_server/sysom_hotfix/apps/hotfix/models.py @@ -80,14 +80,15 @@ class ReleasedHotfixListModule(BaseModel): (1, u'废弃') ] hotfix_id = models.CharField(max_length=50, verbose_name="hotfix id") - released_kernel_version = models.CharField(max_length=60, verbose_name="hotfix发布的内核版本") + released_kernel_version = models.CharField(max_length=180, verbose_name="hotfix发布的内核版本") serious = models.IntegerField(default=0, choices=serious_choice, verbose_name="hotfix推荐安装级别") - description = models.TextField(default="", verbose_name="hotfix问题描述") + serious_explain = models.TextField(default="", verbose_name='推荐说明', blank=True) + description = models.TextField(default="", verbose_name="hotfix问题描述", blank=True) fix_system = models.IntegerField(default=0, choices=system_choice, verbose_name="涉及子系统") released_time = models.DateTimeField(auto_now=False, verbose_name="发布时间") - download_link = models.TextField(default="", verbose_name="hotfix下载链接") + download_link = models.TextField(default="", verbose_name="hotfix下载链接", blank=True) deprecated = models.IntegerField(default=0, choices=deprecated_choice, verbose_name="该hotfix是否被废弃") - deprecated_info = models.TextField(default="", verbose_name="废弃原因或信息") + deprecated_info = models.TextField(default="", verbose_name="废弃原因或信息", blank=True) modified_time = models.DateTimeField(auto_now=True, verbose_name='记录修改时间') modified_user = models.CharField(default="", max_length=20, null=True, verbose_name="用于记录最后一次修改的人") diff --git a/sysom_server/sysom_hotfix/apps/hotfix/serializer.py b/sysom_server/sysom_hotfix/apps/hotfix/serializer.py index 91e716ba6291c28a52322d4ba5282ba43578fa17..c9a776ed2d35fbd8fe7fc3c446c2f438913e32e7 100644 --- a/sysom_server/sysom_hotfix/apps/hotfix/serializer.py +++ b/sysom_server/sysom_hotfix/apps/hotfix/serializer.py @@ -1,4 +1,9 @@ +import os +import tempfile +import pandas as pd from clogger import logger +from django.utils import timezone +from django.core.files.uploadedfile import InMemoryUploadedFile from rest_framework import serializers from apps.hotfix.models import HotfixModel, OSTypeModel, KernelVersionModel, ReleasedHotfixListModule @@ -23,6 +28,185 @@ class KernelSerializer(serializers.ModelSerializer): class ReleasedHotfixSerializer(serializers.ModelSerializer): + deprecated = serializers.SerializerMethodField() + modified_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S") + released_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S") + class Meta: model = ReleasedHotfixListModule fields = '__all__' + + def get_deprecated(self, obj): return bool(obj.deprecated) + + +class CreateReleasedHotfixSerializer(serializers.ModelSerializer): + + deprecated = serializers.BooleanField(default=False) + deprecated_info = serializers.CharField(default="") + + class Meta: + model = ReleasedHotfixListModule + exclude = ['modified_time', 'modified_user'] + + def validate(self, attrs): + deprecated_info = attrs.get('deprecated_info', "") + deprecated = attrs.get('deprecated', False) + if not deprecated and len(deprecated_info) > 0: + raise serializers.ValidationError('Field deprecated is false, deprecated_info is empty!') + + if deprecated and len(deprecated_info) == 0: + raise serializers.ValidationError("Field deprecated is true, field deprecated_info required!") + + return super().validate(attrs) + + def validate_hotfix_id(self, attrs): + instance = ReleasedHotfixListModule.objects.filter(hotfix_id=attrs).first() + if instance is None: + return super().validate(attrs) + else: + raise serializers.ValidationError(detail='Field hotfix_id does not exist') + + def validate_released_kernel_version(self, attrs): + instance = ReleasedHotfixListModule.objects.filter(released_kernel_version=attrs).first() + if instance is None: + return super().validate(attrs) + else: + raise serializers.ValidationError(detail='Field released_kernel_version does not exist') + + +class UpdateReleasedHotfixSerializer(serializers.ModelSerializer): + released_kernel_version = serializers.CharField(required=False) + hotfix_id = serializers.CharField(required=False) + released_time = serializers.DateTimeField(required=False) + + class Meta: + model = ReleasedHotfixListModule + exclude = ['modified_time', 'modified_user'] + + def validate_hotfix_id(self, attrs): + """Filter the data named "hotfix_id" so that it cannot be repeated in the database""" + instance = ReleasedHotfixListModule.objects.filter(hotfix_id=attrs).first() + if instance: + raise serializers.ValidationError(f"field hotfix_id: {attrs} Exist") + else: + return attrs + + def validate(self, attrs): + """ + Filter the data named "released_kernel_version" + so that it cannot be repeated in the database + """ + hotfix_id=attrs.get("hotfix_id",None) + released_kernel_version=attrs.get("released_kernel_version",None) + if hotfix_id and released_kernel_version: + instance_kernel_version=ReleasedHotfixListModule.objects.filter(**attrs) + if instance_kernel_version: + raise serializers.ValidationError(f"released_kernel_version:{released_kernel_version} is already existed!") + return attrs + + +class UpdatePutReleasedHotfixSerializer(serializers.ModelSerializer): + deprecated = serializers.BooleanField() + + class Meta: + model = ReleasedHotfixListModule + exclude = ['modified_time', 'modified_user'] + + def validate_deprecated(self, attrs): + return 1 if attrs else 0 + + def validate(self, attrs): + deprecated_info = attrs.get('deprecated_info', "") + deprecated = attrs.get('deprecated', False) + if not deprecated and len(deprecated_info) > 0: + raise serializers.ValidationError('Field deprecated is false, deprecated_info is empty!') + + if deprecated and len(deprecated_info) == 0: + raise serializers.ValidationError("Field deprecated is true, field deprecated_info required!") + return super().validate(attrs) + + +class BulkImportHotfixReleasedSerializer(serializers.Serializer): + file = serializers.FileField(required=True) + + def __init__(self, instance=None, data=..., **kwargs): + super().__init__(instance, data, **kwargs) + self._file: InMemoryUploadedFile = None + self._save_temporary_file = None + self._suffix: str = None + self._save_file_path = None + self._default_save_path = '/tmp/' + self._suffixs = ['xls', 'csv', 'xlsx'] + self._action = { + 'csv': pd.read_csv, + 'xls': pd.read_excel, + 'xlsx': pd.read_excel + } + + def validate_file(self, file: InMemoryUploadedFile): + """validate param `file`""" + file_name = file.name + self._suffix = file_name.split('.')[-1] + + if self._suffix not in self._suffixs: + raise serializers.ValidationError('file suffix invaild!') + self._file = file + + self._save_upload_file() + try: + context = self._file_parse() + except Exception as e: + raise serializers.ValidationError(f'parse file faid! Error: {e}') + finally: + self.close_file() + return context + + def _save_upload_file(self): + """Save the file to a temporary file""" + self._save_temporary_file = tempfile.NamedTemporaryFile(dir=self._default_save_path) + self._save_file_path = os.path.join(self._default_save_path, self._save_temporary_file.name) + + with open(self._save_file_path, 'wb') as f: + for chunk in self._file.chunks(chunk_size=1024): + f.write(chunk) + + def _file_parse(self) -> [dict]: + """parse the file""" + if self._suffix is None: + raise serializers.ValidationError("file suffix is not none!") + + if self._save_file_path is None: + raise serializers.ValidationError('file save file is not none!') + + context = self._action[self._suffix](self._save_file_path) + return context + + def create(self, validated_data): + """Save the data to the database""" + file_data=validated_data.get("file") + file_header_fields=["hotfix_id","modified_time","released_kernel_version"] + file_headers=set(filter(lambda x: x in file_header_fields, list(file_data))) + if not file_headers == set(file_header_fields): + raise serializers.ValidationError(f"upload files must have {file_header_fields} ,your file only have {file_headers},please check your file!") + data_list=file_data.to_dict(orient='records') + instance_list = [] + for data in data_list: + data.pop("status") + if not data["hotfix_id"] or not data["modified_time"] or not data["released_kernel_version"]: + continue + modified_time=data['modified_time'] + if isinstance(modified_time, str): + modified_time = modified_time.rsplit('.')[0] + data['released_time'] = modified_time if modified_time else timezone.now() + + if not ReleasedHotfixListModule.objects.filter( + hotfix_id=data["hotfix_id"], + released_kernel_version=data['released_kernel_version'] + ): + instance_list.append(ReleasedHotfixListModule(**data)) + return ReleasedHotfixListModule.objects.bulk_create(instance_list) + + def close_file(self): + """delete the temporary file!""" + if self._save_temporary_file: + self._save_temporary_file.close() diff --git a/sysom_server/sysom_hotfix/apps/hotfix/urls.py b/sysom_server/sysom_hotfix/apps/hotfix/urls.py index 09e512fb62cbcc169d8ac2b94cba43a006221064..875623c80965151e5c583d349cb971cbe0edaf39 100644 --- a/sysom_server/sysom_hotfix/apps/hotfix/urls.py +++ b/sysom_server/sysom_hotfix/apps/hotfix/urls.py @@ -35,10 +35,10 @@ urlpatterns = [ path('api/v1/hotfix/rebuild_hotfix/',views.HotfixAPIView.as_view({'post': 'rebuild_hotfix'})), path('api/v1/hotfix/oneclick_deploy/', views.HotfixAPIView.as_view({'post': 'oneclick_deploy'})), path('api/v1/hotfix/health_check/', views.HealthViewset.as_view({'get': 'health_check'})), - path('api/v1/hotfix/get_all_released_hotfix/', views.ReleaseHotfixListAPIView.as_view({'get': 'get_all_released_hotfix'})), + path('api/v1/hotfix/get_released_hotfixs/', views.ReleaseHotfixListAPIView.as_view({'get': 'get_filter_released_hotfixs'})), path('api/v1/hotfix/insert_released_hotfix_info/', views.ReleaseHotfixListAPIView.as_view({'post': 'add_one_released_hotfix'})), - path('api/v1/hotfix/get_filtered_released_hotfix/', views.ReleaseHotfixListAPIView.as_view({'get': 'filter_released_hotfix'})), - path('api/v1/hotfix/import_from_tablefile/', views.ReleaseHotfixListAPIView.as_view({'post': 'import_from_table'})), - path('api/v1/hotfix/update_one_released_hotfix_info/', views.ReleaseHotfixListAPIView.as_view({'post': 'update_released_hotfix_record'})), + path('api/v1/hotfix/import_from_tablefiles/', views.ReleaseHotfixListAPIView.as_view({'post': 'import_from_table_v2'})), + path('api/v1/hotfix/update_put_released_hotfix_info//', views.ReleaseHotfixListAPIView.as_view({'put': 'update_released_hotfix_record'})), + path('api/v1/hotfix/update_patch_released_hotfix_info//', views.ReleaseHotfixListAPIView.as_view({'patch': 'update_released_hotfix_record'})), path('api/v1/', include(router.urls)), ] diff --git a/sysom_server/sysom_hotfix/apps/hotfix/views.py b/sysom_server/sysom_hotfix/apps/hotfix/views.py index de4962277c507c7a85f6da322a1c0a92ac7ba9b2..d3bc9a380bcae98f5c6b10a42634a186d981e706 100644 --- a/sysom_server/sysom_hotfix/apps/hotfix/views.py +++ b/sysom_server/sysom_hotfix/apps/hotfix/views.py @@ -21,7 +21,9 @@ import pandas as pd from apps.hotfix import serializer from apps.hotfix.models import HotfixModel, OSTypeModel, KernelVersionModel, ReleasedHotfixListModule +from apps.hotfix.filters import HotfixReleasedFilter from lib.response import * +from lib.paginations import Pagination from lib.utils import human_datetime, datetime, datetime_str from lib.exception import APIException from lib.base_view import CommonModelViewSet @@ -601,246 +603,67 @@ class HotfixAPIView(GenericViewSet, class HealthViewset(CommonModelViewSet): def health_check(self, request, *args, **kwargs): return success(result={}) - + + class ReleaseHotfixListAPIView(GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): + queryset = ReleasedHotfixListModule.objects.all() + pagination_class = Pagination http_method_names = ['get', 'post', 'patch', 'delete'] serializer_class = serializer.ReleasedHotfixSerializer + filter_class = HotfixReleasedFilter filter_backends = [DjangoFilterBackend] - http_method_names = ['get', 'post', 'patch', 'delete'] - filterset_fields = ['hotfix_id', 'released_kernel_version', 'serious', 'fix_system', 'released_time'] - - def __init__(self, **kwargs: Any) -> None: - super().__init__(**kwargs) - - """this function returns all the records in database + http_method_names = ['get', 'post', 'patch', 'put'] + + def get_serializer_class(self): + """appoint method serializer""" + request_method_dict = { + "POST": serializer.CreateReleasedHotfixSerializer, + "PUT": serializer.UpdatePutReleasedHotfixSerializer, + "PATCH": serializer.UpdateReleasedHotfixSerializer, + "GET": serializer.ReleasedHotfixSerializer, + } + return request_method_dict[self.request.method] + + """this function returns the filtered records in the database """ - def get_all_released_hotfix(self, request): - try: - queryset = ReleasedHotfixListModule.objects.all().filter(deleted_at=None) - all_released_result = serializer.ReleasedHotfixSerializer(queryset, many=True) - except Exception as e: - logger.error(str(e)) - return other_response(message="%s"%str(e), code=400) - return success(result=all_released_result.data, msg={"msg":"get all released hotfix success"}) - + def get_filter_released_hotfixs(self, request: Request, *args, **kwargs): + queryset = self.filter_queryset(self.get_queryset()) + if not queryset: + return success([], total=0) + return super().list(request, *args, **kwargs) + """insert one released hotfix record into database """ - def add_one_released_hotfix(self, request): - hotfix_id = request.data["hotfix_id"] - released_kernel_version = request.data["released_kernel_version"] - serious = request.data["serious"] - description = request.data["description"] - fix_system = request.data["fix_system"] - released_time = request.data["release_time"] - download_link = request.data["download_link"] - # the above information must included - deprecated = request.data["deprecated"] - deprecated_info = request.data["deprecated_info"] - - if (deprecated > 0 and len(deprecated_info) == 0) or (deprecated == 0 and len(deprecated_info) > 0): - logger.error("{} : {}".format(sys._getframe().f_code.co_name, "Invalid deprecated and info status!")) - return other_response(message=("Invalid deprecated and info status!"), code=400) - - try: - # one hotfix id with same kernel version should view as the same hotfix - released_hotfix = ReleasedHotfixListModule.objects.filter(hotfix_id=hotfix_id).filter(released_kernel_version=released_kernel_version).first() - if released_hotfix is None: - released_hotfix = ReleasedHotfixListModule.objects.create( - hotfix_id = hotfix_id, - released_kernel_version = released_kernel_version, - serious = serious, - description = description, - fix_system = fix_system, - released_time = released_time, - download_link = download_link, - deprecated = deprecated, - deprecated_info = deprecated_info - ) - else: - self.update_released_hotfix_record(request=request) - except Exception as e: - logger.error("ERROR: insert released hotfix information. Exception: %s" % str(e) ) - return other_response(message="ERROR:%s"%str(e), code=400) - - return success(result={"msg":"Insert hotfix id : %s success" % hotfix_id}) - - """given parameters, filter the record in database from the given parameter - """ - def filter_released_hotfix(self, request): - search_hotfix_id = request.data.get("search_hotfix_id") if request.data.get("search_hotfix_id") is not None else None - search_kernel_version = request.data.get("search_kernel_version") if request.data.get("search_kernel_version") is not None else None - search_serious = request.data.get("search_serios") if request.data.get("search_serios") is not None else None - search_released_time = request.data.get("search_released_time") if request.data.get("search_released_time") is not None else None - search_fix_system = request.data.get("fix_system") if request.data.get("fix system") is not None else None - try: - queryset = self.function.query_released_hotfix_by_para(search_hotfix_id,search_kernel_version, - search_serious, search_released_time, - search_fix_system) - response = serializer.ReleasedHotfixSerializer(queryset, many=True) - except Exception as e: - logger.error("{} : ERROR: query released hotfix. Exception: {}".format(sys._getframe().f_code.co_name, str(e))) - return other_response(message="Error when query released hotfix information") - return success(result=response.data, message="invoke get_formal_hotfixlist") + def add_one_released_hotfix(self, request, *args, **kwarg): + create_serializer = self.get_serializer(data=request.data) + create_serializer.is_valid(raise_exception=True) + self.perform_create(create_serializer) + ser = serializer.ReleasedHotfixSerializer(create_serializer.instance) + return success(result=ser.data) + """this function is used to update one hotfix record However, the information inside just can update, but cannot delete! You can update it into blank message " ", but I hope this message should never be deleted! """ - def update_released_hotfix_record(self, request): - database_id = request.data["id"] if request.data["id"] is not None else None - hotfix_id = request.data['hotfix_id'] - serious = request.data["serious"] - description = request.data["description"] - fix_system = request.data["fix_system"] - released_time = request.data["release_time"] - download_link = request.data["download_link"] - # the above information must included - deprecated = request.data["deprecated"] - deprecated_info = request.data["deprecated_info"] - - if (deprecated == 0 and len(deprecated_info) > 0) or (deprecated > 0 and len(deprecated_info) == 0): - logger.error("{} : Error : deprecated status and deprecated_info is not the same!".format(sys._getframe().f_code.co_name)) - return other_response(message="Different derepcated status of info and status, id : {}".format(str(hotfix_id))) - - if database_id is None: - logger.error("{} : Error : update relased hotfix with no database id!".format(sys._getframe().f_code.co_name)) - return other_response(message="Error: {} : Cannot update hotfix info with no hotfix id".format(sys._getframe().f_code.co_name)) - - try: - released_hotfix = ReleasedHotfixListModule.objects.filter(id=database_id).first() - if released_hotfix is None: - logger.error("{}: Error: {}".format(sys._getframe().f_code.co_name, "using release hotfix is not exist!")) - return other_response(message="This released hotfix is not exist!",code=400) - released_hotfix.serious = serious - released_hotfix.description = description - released_hotfix.fix_system = fix_system - released_hotfix.released_time = released_time - released_hotfix.download_link = download_link - if deprecated is not None: - released_hotfix.deprecated = deprecated - released_hotfix.deprecated_info = deprecated_info - released_hotfix.save() - except Exception as e: - logger.error("{} : Exception : {}".format(sys._getframe().f_code.co_name, str(e))) - return other_response(message="Error when updating hotfix info, id : %s" % str(hotfix_id)) - - return success(result={"msg":"success updating released hotfix information, id : {}".format(hotfix_id)}) - - - """ - Import Released Hotfix Information from table file - eg. Excel, csv, etc. - """ - def import_from_table(self, request): - # upload the table file - table_file = request.data.get('file', None) - catalogue = request.data.get('catalogue', None) - if not table_file: - return APIException(message="Upload Failed: file required!") - requirement_file_type = ["csv", "xlsx", "xls"] - file_upload_name = table_file.name - file_upload_type = file_upload_name.split(".")[-1] - if file_upload_type not in requirement_file_type: - return other_response(msg=f"file type error, we can not support .{file_upload_type}, please upload correct file type", code=400) - tmp_file_path = "/tmp/" - if not os.path.exists(tmp_file_path): - os.makedirs(tmp_file_path) - patch_file_name = table_file.name.rstrip("."+file_upload_type) + "-" + datetime.now().strftime('%Y%m%d%H%M%S') + "." + file_upload_type - file_path = os.path.join(tmp_file_path, patch_file_name) - try: - with open(file_path, 'wb') as f: - for chunk in file_path.chunks(): - f.write(chunk) - except Exception as e: - logger.error(e) - raise APIException(message=f"Upload Failed: {e}") - - try: - # from now, read the table file data - if file_upload_type in ["csv"]: - # csv file type - df = pd.read_csv(file_path) - all_results = ReleasedHotfixListModule.objects.all() - for index, row in df.iterrows(): - hotfix_id = row[1] - released_kernel_version = row[2] - serious = row[3] - description = row[4] - fix_system = row[5] - released_time = row[6] - download_link = row[7] - deprecated = row[8] - deprecated_info = row[9] - - record = all_results.filter(hotfix_id=hotfix_id).filter(released_kernel_version=released_kernel_version).first() - # if this hotfix with the same kernel is exist, update it - if record: - record.serious = serious - record.description = description - record.fix_system = fix_system - record.released_time = released_time - record.download_link = download_link - record.deprecated = deprecated - record.deprecated_info = deprecated_info - record.save() - else: - # this released record is not exist, create it - record = ReleasedHotfixListModule.objects.create( - hotfix_id = hotfix_id, - released_kernel_version = released_kernel_version, - serious = serious, - description = description, - fix_system = fix_system, - released_time = released_time, - download_link = download_link, - deprecated = deprecated, - deprecated_info = deprecated_info - ) - else: - # excel file type - df = pd.read_excel(file_path) - for index, row in df.iterrows(): - hotfix_id = row[1] - released_kernel_version = row[2] - serious = row[3] - description = row[4] - fix_system = row[5] - released_time = row[6] - download_link = row[7] - deprecated = row[8] - deprecated_info = row[9] - - record = all_results.filter(hotfix_id=hotfix_id).filter(released_kernel_version=released_kernel_version).first() - # if this hotfix with the same kernel is exist, update it - if record: - record.serious = serious - record.description = description - record.fix_system = fix_system - record.released_time = released_time - record.download_link = download_link - record.deprecated = deprecated - record.deprecated_info = deprecated_info - record.save() - else: - # this released record is not exist, create it - record = ReleasedHotfixListModule.objects.create( - hotfix_id = hotfix_id, - released_kernel_version = released_kernel_version, - serious = serious, - description = description, - fix_system = fix_system, - released_time = released_time, - download_link = download_link, - deprecated = deprecated, - deprecated_info = deprecated_info - ) - except Exception as e: - logger.error("Error when sync released hotfix record from file...") - return other_response(message="{} : Error when sync released hotfix record from file...".format(sys._getframe().f_code.co_name), code=400) - - return success(result={"msg":"success sync released hotfix record from file..."}) \ No newline at end of file + def update_released_hotfix_record(self, request, *args, **kwargs): + """appoint patch method""" + partial = kwargs.pop('partial', False) + instance = self.get_object() + update_serializer = self.get_serializer(instance, data=request.data, partial=partial) + update_serializer.is_valid(raise_exception=True) + self.perform_update(update_serializer) + + ser = serializer.ReleasedHotfixSerializer(update_serializer.instance, many=False) + return success(result=ser.data) + + def import_from_table_v2(self, request): + ser = serializer.BulkImportHotfixReleasedSerializer(data=request.data) + ser.is_valid(raise_exception=True) + self.perform_create(ser) + return success(result={},message="save files successful!")