Skip to content
Open
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions filebrowser/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,11 +430,20 @@ def is_empty(self):
return False

# VERSION ATTRIBUTES/PROPERTIES
# version
# is_version
# versions_basedir
# original
# original_filename

@property
def version(self):
"Returns version name"
tmp = self.filename_root.split("_")
if tmp[-1] in VERSIONS:
return tmp[-1]
return None

@property
def is_version(self):
"True if file is a version, false otherwise"
Expand Down
32 changes: 32 additions & 0 deletions filebrowser/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from django.conf import settings
from django.http.response import Http404
from django.shortcuts import redirect
from filebrowser.base import FileObject


class OnDemandMiddleware(object):
"""
Middleware that handles 404 errors of images and generates missing image versions.

If the new version is successfully generated, redirects to generated version url.
This make sure new request is made by browser, and file serving will be done
in ordinary way (probably by web-server).

Just make sure the web-server request is handled by django if the requested file does not exist.
"""

def process_exception(self, request, exception):
# Check that exception is 404 error for file in media folder
if isinstance(exception, Http404) and request.path.startswith(settings.MEDIA_URL):
# Strip MEDIA_URL from path and test if requested path is image version
# with existing original image
relative_path = request.path[len(settings.MEDIA_URL):]
file_obj = FileObject(relative_path)
if file_obj.is_version:
original_obj = file_obj.original
if original_obj.exists:
# Generate requested image version
new_file_obj = original_obj.version_generate(file_obj.version)

# Redirects to generated image URL
return redirect(new_file_obj.url)