Created
September 20, 2011 13:03
-
-
Save alfredo/1229022 to your computer and use it in GitHub Desktop.
Secured downloads with DEBUG fallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def secured_download(func): | |
"""Wraps a view to server files securely ONLY when a | |
``FileField`` is returned | |
Uses Django when ``DEBUG`` is on else NGINX | |
""" | |
def wrapper(request, *args, **kwargs): | |
response = func(request, *args, **kwargs) | |
if isinstance(response, FieldFile): | |
# response is a ``FieldFile`` we should serve it | |
if settings.DEBUG: | |
# only serve through Django when DEBUG is on | |
stream = serve(request, response.name, settings.MEDIA_ROOT) | |
stream['Content-Disposition'] = 'attachment; filename=%s' % \ | |
response.name | |
return stream | |
else: | |
# Use X-Accel-Redirect to serve the file | |
stream = HttpResponse('') | |
stream['X-Accel-Redirect'] = response.url | |
return stream | |
return response | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment