可以用Python在Azure函数Linux消耗计划中保存临时文件吗?

2024-06-11 18:36:14 发布

您现在位置:Python中文网/ 问答频道 /正文

首先为我的英语感到抱歉。我有一个使用Python的Azure Function Linux消费计划,我需要生成一个html,使用wkhtmltopdf转换为pdf并通过电子邮件发送

 #generate temporally pdf
config = pdfkit.configuration(wkhtmltopdf="binary/wkhtmltopdf")
pdfkit.from_string(pdf_content, 'report.pdf',configuration=config, options={})

#read pdf and transform to Bytes
with open('report.pdf', 'rb') as f:
    data = f.read()

#encode bytes
encoded = base64.b64encode(data).decode()

#Send Email
EmailSendData.sendEmail(html_content,encoded,spanish_month)

在我的本地开发中,代码运行正常,但是当我部署函数并执行代码时,我会收到一个错误,错误是:

Result: Failure Exception: OSError: wkhtmltopdf reported an error: Loading pages (1/6) [> ] 0% [======> ] 10% [==============================> ] 50% [============================================================] 100% QPainter::begin(): Returned false Error: Unable to write to destination

我认为报告该错误是因为出于任何原因,写入权限不可用。你能帮我解决这个问题吗

提前谢谢


Tags: toreportconfigreaddatapdfhtml错误
2条回答

tempfile.gettempdir()方法返回一个临时文件夹,,在Linux上是/tmp。应用程序可以使用此目录存储函数在执行过程中生成和使用的临时文件

所以使用/tmp/report.pdf作为文件目录来保存临时文件

with open('/tmp/report.pdf', 'rb') as f:
    data = f.read()

有关更多详细信息,请参阅此article

最终正确代码:

config = pdfkit.configuration(wkhtmltopdf="binary/wkhtmltopdf")

local_path = os.path.join(tempfile.gettempdir(), 'report.pdf')
logger.info(tempfile.gettempdir())

pdfkit.from_string(pdf_content, local_path,configuration=config, options={})

相关问题 更多 >