Google Cloud的Python中的tmp文件 [英] tmp file in Google cloud Functions for Python

查看:82
本文介绍了Google Cloud的Python中的tmp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python在Google云功能上运行得很不错,但是用于tmp文件.这是我的简化代码:

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)

错误是:[Errno 2]没有这样的文件或目录:'/tmp/report.pdf'

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

它在本地工作得很好.不幸的是,文档仅显示节点版本.解决方法也可以用于发送该PDF.

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

推荐答案

找到用于在临时文件夹中编写的Google官方文档有些困难.就我而言,我需要写一个临时目录,然后使用GCF将其上传到Google云存储.

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.

写在Google Cloud Functions的临时目录中,它将消耗为此功能配置的内存资源.

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

创建文件并使用它后,建议将其从临时目录中删除.我使用此代码段在GCF(Python 3.7)中将csv写入临时目录.

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)

这篇关于Google Cloud的Python中的tmp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆