Created
July 19, 2012 14:52
-
-
Save gileno/3144482 to your computer and use it in GitHub Desktop.
Servir arquivos estáticos protegidos com apache (x-sendfile) e django
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
# -*- coding: utf-8 -*- | |
import posixpath | |
import urllib | |
import os | |
from django.conf import settings | |
from django.views.static import serve | |
from django.http import HttpResponse | |
from django.utils.encoding import smart_str | |
USE_XSENDFILE = getattr(settings, 'USE_XSENDFILE', False) | |
def xsendfileserve(request, path, document_root=None): | |
""" | |
Serve static files using X-Sendfile below a given point | |
in the directory structure. | |
""" | |
split = path.split('/') | |
filename = split[-1] | |
filename = filename.replace(" ", '_') | |
if USE_XSENDFILE: | |
if document_root is None: | |
fullpath = smart_str(path) | |
else: | |
fullpath = smart_str(os.path.join(document_root, path)) | |
# This is where the magic takes place. | |
response = HttpResponse() | |
response['X-Sendfile'] = fullpath # for nginx use: X-Accel-Redirect | |
# Unset the Content-Type as to allow for the webserver | |
# to determine it. | |
response['Content-Type'] = '' | |
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename) | |
return response | |
response = serve(request, path, document_root) | |
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment