3

Python runs like a charm on google cloud functions, but for the tmp files. Here's my simplified code:

FILE_PATH = "{}/report.pdf".format(tempfile.gettempdir())
pdf.output(FILE_PATH)
...
with open(FILE_PATH,'rb') as f:
    data = f.read()
    f.close()
encoded = base64.b64encode(data).decode()

attachment = Attachment() 
attachment.content = str(encoded)
attachment.type = "application/pdf"
attachment.filename = "report"
attachment.disposition = "attachment"
attachment.content_id = "Report"

mail = Mail(from_email, subject, to_email, content)
mail.add_attachment(attachment)

Error is: [Errno 2] No such file or directory: '/tmp/report.pdf'

It works perfectly fine locally. Docs unfortunately only shows the node version. Workarounds would also be fine for sending that PDF.

rapsli
  • 749
  • 1
  • 8
  • 23
  • 1
    Why don't you just output your data to a memory stream given that you only use it to base64-encode it for sending via email? – zwer Jul 23 '18 at 22:52
  • 1
    https://stackoverflow.com/questions/42719793/write-temporary-files-from-google-cloud-function – Adarsh Jul 24 '18 at 03:28
  • Will try the stream idea. I have already seen that question on stackoverflow, but it doesn't seem to work – rapsli Jul 24 '18 at 14:13
  • 1
    I replicated your code and same error. Python for CFs is in Beta, so probably it gets fixed in the future. Another workaround that I can think off would be using GC Storage API to read and write. – Iñigo Jul 24 '18 at 15:17
  • good tip. I will give it a try with the stream and will then try gc storage api – rapsli Jul 24 '18 at 21:11
  • seems like fpdf has the possibility to output a byte string: byte_string = pdf.output(dest="S"). But I'm failing to convert this byte string into a valid "pdf attachment" – rapsli Jul 25 '18 at 20:56

1 Answers1

10

It is a little difficult to find Google official documentation for writing in temporary folder. In My case, I needed to write in a temporary directory and upload it to google cloud storage using GCF.

Writing in temporary directory of Google Cloud Functions, it will consume memory resources provisioned for the function.

After creating the file and using it, it is recommended to remove it from the temporary directory. I used this code snippet for Write a csv into a temp dir in GCF(Python 3.7).

import pandas as pd
import os
import tempfile
from werkzeug.utils import secure_filename


def get_file_path(filename):
    file_name = secure_filename(filename)
    return os.path.join(tempfile.gettempdir(), file_name)

def write_temp_dir():
    data = [['tom', 10], ['nick', 15]] 
    df = pd.DataFrame(data, columns = ['Name', 'Age'])
    name = 'example.csv'
    path_name = get_file_path(name)
    df.to_csv(path_name, index=False)
    os.remove(path_name)
Luiz Lai
  • 384
  • 4
  • 10