Created
July 8, 2011 08:53
-
-
Save ViktorStiskala/1071390 to your computer and use it in GitHub Desktop.
XSendFileResponse for Django with fallback when XSendFile is disabled
This file contains hidden or 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
from django.http import HttpResponse | |
from mimetypes import guess_type | |
import settings | |
import re, os | |
class XSendFileError(Exception): | |
pass | |
class XSendFileResponse(HttpResponse): | |
def __init__(self, file_path, content_type=None): | |
if not os.path.exists(file_path): | |
raise IOError('File does not exist') | |
# convert path | |
file_path = os.path.realpath(file_path) | |
if not content_type: | |
content_type = guess_type(file_path)[0] | |
try: | |
settings.USE_XSENDFILE and settings.XSENDFILE_ROOT | |
except AttributeError: | |
raise XSendFileError('XSENDFILE_ROOT is required when USE_XSENDFILE is enabled') | |
# XSendFile disabled, read the content and pass it to browser | |
if not settings.USE_XSENDFILE: | |
f = open(file_path, 'r') | |
content = f.read() | |
else: | |
content = '' | |
super(XSendFileResponse, self).__init__(content=content, content_type=content_type) | |
# add X-Sendfile header if enabled | |
if settings.USE_XSENDFILE: | |
path = re.sub(r'^' + os.path.realpath(settings.XSENDFILE_ROOT) + r'/?', '', file_path) | |
self['X-Sendfile'] = path | |
else: | |
self['Content-Length'] = os.path.getsize(file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment