Как прикрепить сгенерированный PDF с Reportlab к электронной почте в App Engine Python - PullRequest
3 голосов
/ 02 марта 2012

У меня есть метод, который генерирует файл PDF с использованием библиотеки Reportlab:

def obtenerPDFNuevoPedido(self, handler,rsUsuarioPedido, rsPedido):
    handler.response.headers['Content-Type'] = 'application/pdf'
    handler.response.headers['Content-Disposition'] = 'attachment; filename=output.pdf'
    story = []
    story.append(Paragraph('CHIPAS', ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=20)))
    story.append(Paragraph('____________ENLANUBE', ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=20)))
    story.append(Spacer(6, 22))
    story.append(Table([[Paragraph(str(strftime("%Y-%m-%d", gmtime())), ParagraphStyle(name="centeredStyle", alignment=TA_LEFT, fontSize=7)), 
    Paragraph(str(strftime("%H:%M:%S", gmtime())), ParagraphStyle(name="centeredStyle", alignment=TA_RIGHT, fontSize=7))]],colWidths=[5.05 * cm, 3.1 * cm]))
    story.append(Paragraph("DEVELOPED AT ROSHKA-LABS", ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=6)))
    story.append(Paragraph('-'*50, styleCentered))
    #...
    #...
    doc = SimpleDocTemplate(handler.response.out, pagesize=letter)
    doc.build(story) 

, когда я вызываю этот метод, он открывает диалоговое окно сохранения, где я могу указать, где файл должен быть сохранен.

Как мне сделать, чтобы прикрепить сгенерированный PDF-файл к электронной почте?

Я видел этот пример:

from google.appengine.api import urlfetch
from google.appengine.api import mail  

url = "http://www.abc.com/files/file.pdf" 
result = urlfetch.fetch(url)

if result.status_code == 200: 
  document = result.content

mail.send_mail(sender="youremail@yourdomain.com",
               to="receiver@hisdomain.com",
               subject="The file you wanted",
               body="Here is the file you wanted",
               attachments=[("The file name.pdf", document)])

Но я не знаю, как применить его в данном конкретном случае.case.

Заранее спасибо!

РЕШЕНИЕ:

Основываясь на предложении @ Хесуса, я решил проблему следующим образом:

class PdfTable(db.Model):
    fecha = db.DateTimeProperty(auto_now_add=True)
    archivoBlob = db.BlobProperty()

def obtenerPDFNuevoPedido(self, handler,rsUsuarioPedido, rsPedido):
#1)I generated the PDF this way:
        styleCentered = ParagraphStyle(name="centeredStyle", alignment=TA_CENTER)
        styleCenteredLeft = ParagraphStyle(name="centeredStyle", alignment=TA_LEFT)
        styleCenteredRight = ParagraphStyle(name="centeredStyle", alignment=TA_RIGHT)

        story = []
        story.append(Paragraph('CHIPAS', ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=20)))
        story.append(Paragraph('____________ENLANUBE', ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=20)))
        story.append(Spacer(6, 22))
        story.append(Table([[Paragraph(str(strftime("%Y-%m-%d", gmtime())), ParagraphStyle(name="centeredStyle", alignment=TA_LEFT, fontSize=7)), Paragraph(str(strftime("%H:%M:%S", gmtime())), ParagraphStyle(name="centeredStyle", alignment=TA_RIGHT, fontSize=7))]],colWidths=[5.05 * cm, 3.1 * cm]))
        story.append(Paragraph("DEVELOPED AT ROSHKA-LABS", ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=6)))
        story.append(Paragraph('-'*50, styleCentered))
        data = [[Paragraph("Usuario",ParagraphStyle(name="centeredStyle", alignment=TA_LEFT, fontSize=7)), Paragraph("Producto/Precio/Cantidad",ParagraphStyle(name="centeredStyle", alignment=TA_LEFT, fontSize=7)),Paragraph("Total", ParagraphStyle(name="centeredStyle", alignment=TA_RIGHT, fontSize=7))]]
        #
        #
        #
#2)Inside the same method, I saved the PDF file in the Datastore       
        pdf = StringIO.StringIO()

        doc = SimpleDocTemplate(pdf, pagesize=letter)
        doc.build(story)

        content = pdf.getvalue()

        blob = model.PdfTable()
        blob.archivoBlob = db.Blob(content)
        blob.put()
#3)The file recently stored  in the datastore was attached like this:        
        mail.send_mail(sender="youremail@yourdomain.com",
               to="receiver@hisdomain.com",
               subject="The file you wanted",
               body="Here is the file you wanted",
               attachments=[('resumen_pedido.pdf'), blob.archivoBlob)])

Хотя я не знаю, является ли это более эффективным способом решения проблемы ... но он работает

Ответы [ 2 ]

4 голосов
/ 10 января 2013

Нет необходимости писать в Blobstore. Просто используйте тип файла cStringIO для хранения содержимого вашего pdf, затем выведите значение с помощью .get_value ()

self.result = cStringIO.StringIO() 
self.pdf = pisa.pisaDocument(cStringIO.StringIO(self.html.encode("UTF-8")), self.result,encoding='UTF-8')
mail.send_mail,sender_address, to_address, subject, body,attachments=[(file_name,self.result.get_value())]
2 голосов
/ 02 марта 2012

Я думаю, что правильный способ сделать это:

  • Создание файла PDF (первый фрагмент кода)
  • Сохраните файл PDF в хранилище данных.
  • Используйте второй фрагмент кода, чтобы прикрепить PDF к электронному письму.

Попробуй и скажи нам =)

...