Skip to content

Commit

Permalink
Add support for direct serving
Browse files Browse the repository at this point in the history
  • Loading branch information
Szaki committed Aug 21, 2024
1 parent 3d761fa commit a4f2015
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
7 changes: 4 additions & 3 deletions binder/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,12 +825,13 @@ class BinderFileField(FileField):
attr_class = BinderFieldFile
descriptor_class = BinderFileDescriptor

def __init__(self, allowed_extensions=None, *args, **kwargs):
def __init__(self, allowed_extensions=None, serve_direct=False, *args, **kwargs):
# Since we also need to store a content type and a hash in the field
# we up the default max_length from 100 to 200. Now we store also
# the original file name, so lets make it 400 chars.
kwargs.setdefault('max_length', 400)
self.allowed_extensions = allowed_extensions
self.serve_direct = serve_direct
return super().__init__(*args, **kwargs)

def get_prep_value(self, value):
Expand Down Expand Up @@ -903,11 +904,11 @@ class BinderImageField(BinderFileField):
descriptor_class = BinderImageFileDescriptor
description = _("Image")

def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, allowed_extensions=None, **kwargs):
def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, allowed_extensions=None, serve_direct=False, **kwargs):
self.width_field, self.height_field = width_field, height_field
if allowed_extensions is None:
allowed_extensions = ['png', 'gif', 'jpg', 'jpeg']
super().__init__(allowed_extensions, verbose_name, name, **kwargs)
super().__init__(allowed_extensions, serve_direct, verbose_name, name, **kwargs)

def check(self, **kwargs):
return [
Expand Down
7 changes: 6 additions & 1 deletion binder/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2878,12 +2878,17 @@ def dispatch_file_field(self, request, pk=None, file_field=None):
guess = mimetypes.guess_type(file_field.path)
guess = guess[0] if guess and guess[0] else 'application/octet-stream'
try:
resp = StreamingHttpResponse(open(file_field.path, 'rb'), content_type=guess)
if file_field.serve_direct:
resp = HttpResponse(content_type=guess)
else:
resp = StreamingHttpResponse(open(file_field.path, 'rb'), content_type=guess)
except FileNotFoundError:
logger.error('Expected file {} not found'.format(file_field.path))
raise BinderNotFound(file_field_name)

if 'download' in request.GET:
if file_field.serve_direct:
resp['X-Accel-Redirect'] = '/internal/media/' + file_field.name
filename = self.filefield_get_name(instance=obj, request=request, file_field=file_field)
if 'prefix' in request.GET:
filename = request.GET['prefix'] + ' - ' + filename
Expand Down

0 comments on commit a4f2015

Please sign in to comment.