import os, urllib from django.core.servers.basehttp import FileWrapper from django.http import HttpResponse class HttpResponseSendfile(HttpResponse): """ HttpResponse for using X-Sendfile. Uses FileWrapper as a fallback if the front-end server doesn't intercept X-Sendfile headers. """ def __init__(self, path, mimetype=None, content_type=None, fallback=True): exists = os.path.exists(path) status = 200 if exists else 404 # Fallback for lack of X-Sendfile support content = '' if exists and fallback: content = FileWrapper(open(path, 'rb')) # Common elements super(HttpResponseSendfile, self).__init__(content, mimetype, status, content_type) self['Content-Length'] = os.path.getsize(path) if exists else 0 filename = urllib.quote(os.path.basename(path).encode('utf8')) self['Content-Disposition'] = 'attachment; filename="%s"' % filename # X-Sendfile self['X-Sendfile'] = path