生成多个文档(Python临时文件模块)

2024-09-30 06:15:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试使用我的web应用程序打印财务报告-这需要通过单击按钮来实现。但是,当我单击按钮时,应用程序只打印1个文档(第一个文档),我不明白这是什么,因为每个if语句都有2个不同的返回,返回到2个不同的.HTML页面

这就是我目前所尝试的:

import tempfile
def printReports(request , reports_pk):
    pkForm = get_object_or_404(SettingsClass , pk=reports_pk)

    complexName = pkForm.Complex
    if pkForm.Trial_balance_Year_To_Date == True:
        ### Printing Trial Balance PDF
        response = HttpResponse(content_type= 'application/pdf')
        response['Content-Disposition']= 'attachment; filename=TrialBalance' + \
            str(datetime.now()) + '.pdf'
        response['Content-Transfer-Encoding'] = 'binary'

        content =  {"x_AlltrbYTD":x_AlltrbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero , 'printDesc':printDesc , 'printAcc':printAcc}
        html_string=render_to_string('main/reports/trialBalanceYear.html' , content)
        html=HTML(string=html_string)

        result=html.write_pdf()

        with tempfile.NamedTemporaryFile(delete=True) as output:
            output.write(result)
            output.flush()

            output.seek(0)
            response.write(output.read())

            return response

    if pkForm.Trial_balance_Monthly == True:
       
        ### Printing Trial Balance PDF
        response = HttpResponse(content_type= 'application/pdf')
        response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \
            str(datetime.now()) + '.pdf'
        response['Content-Transfer-Encoding'] = 'binary'

        content =  {"xtrbMonth":xtrbMonth , 'xCreditTotalM':xCreditTotalM , 'xDebitTotalM':xDebitTotalM , 'complexName':complexName , 'printZeroM':printZeroM}
        html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content)
        html=HTML(string=html_string)

        result=html.write_pdf()

        with tempfile.NamedTemporaryFile(delete=True) as output:
            output.write(result)
            output.flush()

            output.seek(0)
            response.write(output.read())

    else:
        printTrialBalanceMonth = False

程序只打印第一个if语句显示的内容,不打印第二个.pdf文档。有人知道这可能是什么原因吗


Tags: trueoutputstringifpdfresponsehtmlresult
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:39

您正在第一个if块中使用return

Django生成一个响应,下面返回的代码永远不会运行(顺便说一句,它什么也不返回,所以即使pkForm.Trial_balance_Monthly == True也不会有响应

现代IDE(如Pycharm)将在此处向您显示彩色警告,但如果您不使用此类IDE,则可以使用调试器跟踪代码中发生的情况

要进行如您所述的交互(仅一个按钮和两个报告),您需要:

  1. 为2个报告创建2个不同的端点
  2. 编写JS处理程序,监听按钮的点击并调用2个点。像往常一样处理响应

备选方案:

创建一个包含两个报告的临时zip文件,并仅使用一个zip文件创建响应。 每个操作系统都有解压功能,因此您的用户会发现这非常直观

相关问题 更多 >

    热门问题