tmp file in Google cloud Functions for Python

对着背影说爱祢 提交于 2020-01-24 19:32:09

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/51487885/tmp-file-in-google-cloud-functions-for-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!