excel 最好的方法是不要违反DRY原则,Django/基于类的视图

xesrikrc  于 2023-02-05  发布在  Go
关注(0)|答案(1)|浏览(117)

这里是一个视图,我用来下载Excel文档的基础上关闭数据,我有:

class ExcelDownloadAllView(TemplateView):
    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="All_of_Projects.xls"'

        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('All Projects Data') # this will make a sheet named Users Data

        # Sheet header, first row
        row_num = 0

        font_style = xlwt.XFStyle()
        font_style.font.bold = True

        columns = ['Username', 'First Name', 'Last Name', 'Email Address', 'Summary']
        rows = BugTracker.objects.all().values_list('project_number','assignee','priority','status','summary',) 

        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column 

        # Sheet body, remaining rows
        font_style = xlwt.XFStyle()
        for row in rows:
            row_num += 1
            for col_num in range(len(row)):
                ws.write(row_num, col_num, row[col_num], font_style)

        wb.save(response)

        return response

它工作得很好,但是现在我想用不同的“row=”过滤器创建另一个CBV。使用DRY原则做这件事的最好方法是什么?
我尝试了类似的方法,但是rows变量会被前面的类覆盖。

class ExcelDownloadOpenView(ExcelDownloadAllView):
    
    def get(self, request, *args, **kwargs):
        rows = BugTracker.objects.all().values_list('project_number','assignee', 'priority')
        return super().get(request, *args, **kwargs)

在不复制整个方法和替换rows变量的情况下,有什么建议吗?

huwehgph

huwehgph1#

编写一个函数来创建一个文件并将其附加到响应中,并将此函数放在外部文件中以清理代码。例如,假设一个名为core的模块(app):
utils.py

import  xlwt
from django.http import HttpResponse

def create_sheet_response(columns, rows, filename):
    response = HttpResponse(headers={
        'Content-Type': 'application/vnd.ms-excel',
        'Content-Disposition': f'attachment; filename={filename}',
    })

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('All Projects Data')

    row_num = 0

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)

    return response

views.py:

from core.models import BugTracker
from core.utils import create_sheet_response

from django.views.generic import TemplateView

class ExcelDownloadAllView(TemplateView):
    def get(self, request, *args, **kwargs):
        filename = 'All_of_Projects.xls'
        columns = ['Username', 'First Name', 'Last Name', 'Email Address', 'Summary']

        fields = 'project_number','assignee','priority','status','summary'
        rows = BugTracker.objects.all().values_list(*fields)

        return create_sheet_response(columns, rows, filename)

class ExcelDownloadOpenView(TemplateView):
    def get(self, request, *args, **kwargs):
        filename = 'NotAll_of_Projects.xls'
        columns = ['Username', 'First Name', 'Last Name']

        fields = 'project_number','assignee', 'priority'
        rows = BugTracker.objects.all().values_list(*fields)

        return create_sheet_response(columns, rows, filename)

相关问题