Skip to content

Instantly share code, notes, and snippets.

@alfredo
Created September 20, 2011 13:03
Show Gist options
  • Save alfredo/1229022 to your computer and use it in GitHub Desktop.
Save alfredo/1229022 to your computer and use it in GitHub Desktop.
Secured downloads with DEBUG fallback
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