You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GAE Django中使用FPDF无法写入tmp目录生成PDF的问题

问题描述

Django项目使用fpdf包生成PDF,项目结构如下:

  • project:存放所有配置文件
  • apps:存放所有应用文件夹,例如apps/account/views.py、apps/profile/views.py
  • static:静态文件目录
  • template:模板文件目录
  • tmp:临时目录

对应的视图类代码:

class PdfCreater(View):
   def get(self, request, *args, **kwargs):
     pdf = FPDF('P', 'mm', 'Letter')
     pdf.add_page()
     pdf.set_font('helvetica', 'BIU', 16)
     pdf.set_text_color(220,50,50)
     pdf.cell(100, 80, 'Hello World jaskaran singh!' )
     pdf.set_font('times', '', 12)
     pdf.cell(80, 10, 'Good Bye World!')
     path = str(settings.XYZ)

     pdf.output( path+ '/tmp/pdf_2.pdf')
     data = 'try' 

     return JsonResponse({"data": str(path), "header": data})

本地环境中能在tmp目录成功创建pdf_2.pdf,但部署到Google App Engine(GAE)后无法生成文件,报错:

OSError at /converter/PdfCreater
[Errno 30] Read-only file system: '/workspace/tmp/pdf_2.pdf'

根据GAE官方文档说明,tmp目录支持写入操作,但实际无法生效,请问原因是什么?

问题原因与解决方案

核心原因

GAE标准环境中,你代码里指定的path + '/tmp/pdf_2.pdf'指向的是项目目录下的tmp文件夹,而GAE的应用部署目录是只读的,不允许写入操作。官方文档提到的可写入tmp目录是系统级别的临时目录(路径为/tmp),并非你项目自身的tmp文件夹。

修复步骤

  1. 使用系统临时目录:
    替换代码中的路径生成逻辑,改用GAE允许写入的系统临时目录,示例代码如下:

    import os
    import tempfile
    from django.conf import settings
    from django.http import JsonResponse
    from django.views import View
    from fpdf import FPDF
    
    class PdfCreater(View):
       def get(self, request, *args, **kwargs):
         pdf = FPDF('P', 'mm', 'Letter')
         pdf.add_page()
         pdf.set_font('helvetica', 'BIU', 16)
         pdf.set_text_color(220,50,50)
         pdf.cell(100, 80, 'Hello World jaskaran singh!' )
         pdf.set_font('times', '', 12)
         pdf.cell(80, 10, 'Good Bye World!')
         
         # 获取系统临时目录路径
         temp_dir = tempfile.gettempdir()  # 等价于直接使用'/tmp'
         pdf_path = os.path.join(temp_dir, 'pdf_2.pdf')
         pdf.output(pdf_path)
    
         return JsonResponse({"data": temp_dir, "header": "try"})
    
  2. 注意事项:

    • GAE的系统临时目录是实例专属的,当实例被销毁时,目录内的文件会被自动删除,不适合持久化存储。
    • 如果需要长期保存生成的PDF,建议将文件上传至Google Cloud Storage,再返回存储链接给用户。

内容的提问来源于stack exchange,提问作者Jaskaran Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:20:03