Search code examples
pyramid

Pyramid FileResponse for dynamic files


I want my client to download (not render) a dynamically generated PDF file via pyramid. Right now I do it like this:

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

From the client point-of-view it's exactly what I need. However,

  1. It leaves behind an orphaned file
  2. It isn't thread-safe (though I could use random filenames)

The docs say:

class FileResponse

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

So FileResponse is probably not what I should be using. How would you replace it with something more dynamic but indistinguishable for the client?


Solution

  • Just use a normal response with the same header:

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