Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Download template error #2083

Merged
merged 1 commit into from
Jan 23, 2025
Merged

fix: Download template error #2083

merged 1 commit into from
Jan 23, 2025

Conversation

shaohuzhang1
Copy link
Contributor

fix: Download template error --bug=1051908 --user=王孝刚 【知识库】导出的文档打开后里面为错误日志,无文档内容,导出的压缩包不能解压 https://www.tapd.cn/57709429/s/1650087

--bug=1051908 --user=王孝刚 【知识库】导出的文档打开后里面为错误日志,无文档内容,导出的压缩包不能解压 https://www.tapd.cn/57709429/s/1650087
Copy link

f2c-ci-robot bot commented Jan 23, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

Copy link

f2c-ci-robot bot commented Jan 23, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@wxg0103 wxg0103 merged commit 4610be9 into main Jan 23, 2025
4 checks passed
@wxg0103 wxg0103 deleted the pr@main@fix_template branch January 23, 2025 03:07
content = file.read()
file.close()
return HttpResponse(content, status=200, headers={'Content-Type': 'text/cxv',
'Content-Disposition': 'attachment; filename="csv_template.csv"'})
elif self.data.get('type') == 'excel':
file = open(os.path.join(PROJECT_DIR, "apps", "dataset", 'template', _('MaxKB table template.xlsx')),
file = open(os.path.join(PROJECT_DIR, "apps", "dataset", 'template',
f'table_template_{to_locale(language)}.xlsx'),
"rb")
content = file.read()
file.close()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code contains several improvements, corrections, and optimizations:

  1. Translation Functions: The use of get_message has been replaced with gettext_lazy. This is more efficient because it only retrieves the translated message if it's actually needed.

  2. Locale-Specific File Names: The to_locale function ensures that filenames include the locale information (e.g., _template_jp.csv) which can be useful for internationalization.

  3. Path Formatting: Fixed an error where the path was not properly formatted when constructing the full file paths, particularly in Excel templates.

  4. Removed Unnecessary Imports: Removed unused imports such as gettext.

  5. Improved Code Readability: Minor adjustments made for better readability and maintainability.

Here's the revised version:

from django.db.models import QuerySet, Count
from django.db.models.functions import Substr, Reverse
from django.http import HttpResponse
from django.utils.translation import gettext_lazy as _
from drf_yasg import openapi
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
from rest_framework import serializers

parse_qa_handle_list = [XlsParseQAHandle(), CsvParseQAHandle(), XlsxParseQAHandle(), ZipParseQAHandle()]
parse_table_handle_list = [CsvSplitTableHandle(), XlsSplitTableHandle(), XlsxSplitTableHandle()]

def get_request_params_api():
    class ExportSerializer(serializers.Serializer):
        type = serializers.CharField(required=True)

        def export(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            
            language = get_language()

            if self.validated_data['type'] == 'csv':
                with open(f'{PROJECT_DIR}/apps/dataset/template/csv_template_{locale}.csv', 'rb') as file:
                    content = file.read()
                    return HttpResponse(content, status=200, headers={
                        'Content-Type': 'text/csv',
                        'Content-Disposition': f'attachment; filename="csv_template{locale}.csv"'
                    })
            elif self.validated_data['type'] == 'excel':
                with open(f'{PROJECT_DIR}/apps/dataset/template/excel_template_{locale}.xlsx', 'rb') as file:
                    content = file.read()
                    return HttpResponse(content, status=200, headers={
                        'Content-Type': 'application/vnd.ms-excel',
                        'Content-Disposition': f'attachment; filename="excel_template{locale}.xlsx"'
                    })

        def table_export(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
                
            language = get_language()

            if self.validated_data['type'] == 'csv':
                with open(f'{PROJECT_DIR}/apps/dataset/template/table_template_{locale}.csv', 'rb') as file:
                    content = file.read()
                    return HttpResponse(content, status=200, headers={
                        'Content-Type': 'text/cxv',
                        'Content-Disposition': f'attachment; filename="table_template{locale}.csv"'
                    })
            elif self.validated_data['type'] == 'excel':
                with open(f'{PROJECT_DIR}/apps/dataset/template/table_template_{locale}.xlsx', 'rb') as file:
                    content = file.read()
                    return HttpResponse(content, status=200, headers={
                        'Content-Type': 'application/vnd.ms-excel',
                        'Content-Disposition': f'attachment; filename="table_template{locale}.xlsx"'
                    })

export_serializer_instance = ExportSerializer(data=request.data, context={'request': request}) # Assuming this line is part of your request processing

Key Improvements:

  • Localization Support: Use locale to dynamically construct file names, enhancing support for different languages.
  • Code Clarity: Improved formatting for better readability.
  • Efficiency: Used Python's built-in string interpolation using {} syntax for file name construction.

These changes should improve both the performance and usability of the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants