动态文件的 Pyramid FileResponse

Pyramid FileResponse for dynamic files

我希望我的客户通过金字塔下载(而不是呈现)动态生成的 PDF 文件。现在我是这样做的:

def get_pdf(request):
    pdfFile = open('/tmp/example.pdf', "wb")
    pdfFile.write(generator.GeneratePDF())

    response = FileResponse('/tmp/example.pdf')
    response.headers['Content-Disposition'] = ('attachment;  filename=example.pdf')
    return response

从客户的角度来看,这正是我所需要的。然而,

  1. 它留下了一个孤立的文件
  2. 它不是线程安全的(尽管我可以使用随机文件名)

docs 说:

class FileResponse

A Response object that can be used to serve a static file from disk simply.

所以 FileResponse 可能不是我应该使用的。您将如何用更动态但对客户来说无法区分的东西替换它?

只需使用具有相同 header:

的正常回复
def get_pdf(request):
    response = Response(body=generator.GeneratePDF())
    response.headers['Content-Disposition'] = ('attachment;filename=example.pdf')
    return response