rap*_*sli 3 python-3.x google-cloud-functions
Python 在 google 云函数上的运行就像一个魅力,但对于 tmp 文件。这是我的简化代码:
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)
Run Code Online (Sandbox Code Playgroud)
错误是:[Errno 2] 没有这样的文件或目录:'/tmp/report.pdf'
它在本地运行良好。不幸的是,文档仅显示节点版本。解决方法也可以发送该 PDF。
小智 10
在临时文件夹中找到谷歌官方文档有点困难。就我而言,我需要写入一个临时目录并使用 GCF 将其上传到谷歌云存储。
在 Google Cloud Functions 的临时目录中写入,它将消耗为该函数配置的内存资源。
创建文件并使用后,建议将其从临时目录中删除。我使用此代码片段将 csv 写入 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3415 次 |
| 最近记录: |