使用xhtml2pdf

时间:2019-04-26 17:05:47

标签: python django email xhtml2pdf

我正在尝试将pdf文件附加到Django中的电子邮件中。 pdf是使用xhtml2pdf从html视图呈现的。

每天使用调度程序从Heroku中调用该脚本。这部分工作正常。

我遇到的问题是从Django中的管理/命令脚本调用pdf时将其附加到电子邮件中。

或者真正的问题是如何从视图中检索pdf而不调用PDFReport.as_view(),因为这不是Bytes文件而是渲染函数。

urls.py

path('pdf_report/', PDFReport.as_view(), name="Pdf_report"),

views.py

class PDFReport(View):
    def get(self, request, airport_code=None, date_code=None, shift_code=None):

        dates = get_perf_dates(date_code)

    # Render the resulting json data
        params = {'p_table': p_table,
                  "airportcode": airport_code,
                  "perfdates": dates,
                  "shift": shift_code
                 }

        return Render.render('pdf_report.html', params)

render.py

class Render:
    @staticmethod
    def render(path: str, params: dict):
        template = get_template(path)
        html = template.render(params)
        response = BytesIO()
        pdf = x_pisa.pisaDocument(BytesIO(html.encode("UTF-8")), response)
        if not pdf.err:
            return HttpResponse(response.getvalue(), content_type='application/pdf')
        else:
            return HttpResponse("Error Rendering PDF", status=400)

最后是自动化脚本部分(在管理/命令中)

Send_PDF.py

from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from ...views import PDFReport
from ...models import DistributionList

class Command(BaseCommand):
    help = "Sends out an email when called"
    def handle(self, *args, **options):
        '''Contact page view for technical support requests'''
        mail_d_list = []
        for users in DistributionList.objects.all(): #.values_list('email', flat=True)
            mail_d_list.append(users.email)
            mail_name.append(users.name)
        self.stdout.write(str(mail_d_list)) # For testing purposes
        mail_subject = "Daily Report"
        mail_content = "This is an automated message."
        mail_from = 'XXX@gmail.com'
        mail_attachment = PDFReport.as_view()

        email = EmailMessage(mail_subject,
                             mail_content,
                             mail_from,
                             mail_d_list,
                            )
        email.attach('report.pdf', mail_attachment, 'application/pdf')
        email.send()

这将返回一个

TypeError:预期的类似字节的对象,不起作用

0 个答案:

没有答案