webapp2 - 只读文件系统错误

时间:2016-03-20 20:53:51

标签: python google-app-engine jinja2 webapp2

我正在使用Python开发Google App Engine应用程序(webapp2)& Jinja2和我正在尝试使用 reportlab 库创建 PDF 文件。

示例:

from reportlab.pdfgen import canvas

class pdf(webapp2.RequestHandler):
  def get(self):
    x = 50
    y = 750
    c = canvas.Canvas("file.pdf")
    c.drawString(x*5,y,"Output")
    c.line(x,y-10,x*11,y-10)
    c.save()

当我运行服务器时,我收到以下错误:

raise IOError(errno.EROFS, 'Read-only file system', filename)
IOError: [Errno 30] Read-only file system: u'file.pdf'

2 个答案:

答案 0 :(得分:3)

您无法写入appengine文件系统 - 毕竟,由于您有多台计算机(并且您无法始终保证相同的计算机),您会写入哪台计算机的文件系统?

但是,看起来reportlab canvas接受一个打开的文件对象。我无法保证这会起作用,但您可以尝试传递一个类似于打开文件的对象。例如io.BytesIO甚至是webapp2.Response.out

import io
class pdf(webapp2.RequestHandler):
  def get(self):
    x = 50
    y = 750
    c = canvas.Canvas(self.response.out)
    c.drawString(x*5,y,"Output")
    c.line(x,y-10,x*11,y-10)
    c.save()

答案 1 :(得分:1)

我使用StringIO

开始工作
from reportlab.pdfgen import canvas

# Import String IO which is a
# module that reads and writes a string buffer
# cStringIO is a faster version of StringIO
from cStringIO import StringIO

class pdf(webapp2.RequestHandler):
  def get(self):
    pdfFile = StringIO()

    x = 50
    y = 750
    c = canvas.Canvas(pdfFile)
    c.drawString(x*5,y,"Output")
    c.line(x,y-10,x*11,y-10)
    c.save()

    self.response.headers['content-type'] = 'application/pdf'
    self.response.headers['Content-Disposition'] = 'attachment; filename=file.pdf'
    self.response.out.write(pdfFile.getvalue())