Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically close underlying file object when response closes #12

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions ranged_fileresponse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ def __init__(self, file_like, start=0, stop=float('inf'), block_size=None):
block_size (Optional[int]): The block_size to read with.
"""
self.f = file_like
self.size = len(self.f.read())
# If size property available (ie: Django File, FieldFile, etc) and not zero (if zero, double-check anyway)
if hasattr(self.f, 'size') and self.f.size > 0:
self.size = self.f.size
else:
self.size = len(self.f.read())
self.block_size = block_size or RangedFileReader.block_size
self.start = start
self.stop = stop
Expand Down Expand Up @@ -88,12 +92,20 @@ def parse_range_header(self, header, resource_size):

return ranges

def close(self):
"""Close underlying file object"""
if hasattr(self.f, 'close'):
self.f.close()


class RangedFileResponse(FileResponse):
"""
This is a modified FileResponse that returns `Content-Range` headers with
the response, so browsers that request the file, can stream the response
properly.

Note: When using RangedFileResponse with django tests, make sure to read the response.streaming_content after the
request, otherwise the underlying file won't be auto-closed.
"""

def __init__(self, request, file, *args, **kwargs):
Expand All @@ -107,7 +119,6 @@ def __init__(self, request, file, *args, **kwargs):
"""
self.ranged_file = RangedFileReader(file)
super(RangedFileResponse, self).__init__(self.ranged_file, *args, **kwargs)

if 'HTTP_RANGE' in request.META:
self.add_range_headers(request.META['HTTP_RANGE'])

Expand Down