Regarding FileResponse and compressed file objects. Bug?

41 views
Skip to first unread message

Zachary J.

unread,
Oct 30, 2018, 6:28:01 PM10/30/18
to Django users
Consider this situation:

import gzip
from django.http import FileResponse


def some_request(request):
   
return FileResponse(
        gzip
.open('/path/to/filename.gz'),
        content_type
="text/plain",
        filename
="filename.txt",
        as_attachment
=True
   
)


This theoretically should work fine, because why shouldn't it?


if os.path.isabs(filename):
   
self['Content-Length'] = os.path.getsize(filelike.name)
elif hasattr(filelike, 'getbuffer'):
   
self['Content-Length'] = filelike.getbuffer().nbytes

Which gets the file size of the compressed gzip file. (the elif branch is never run) That means that the Content-Length will be shorter than the uncompressed content that I am actually sending.

My current "dumb" solution is as such:

from io import BytesIO
import shutil


def some_request(request):
    buff
= BytesIO()
    with gzip.open('/path/to/filename.gz') as g:
        shutil.copyfileobj(g, buff)
    buff
.seek(0)

    return FileResponse(
        buff,
        content_type
="text/plain",
        filename
="filename.txt",
        as_attachment
=True
   
)

This reads all the uncompressed content into a separate file-like object that does not have the original file name information. Which forces FileResponse to run the elif branch. Is there a better way to do things?
Reply all
Reply to author
Forward
0 new messages