2010-11-23 09:23:40 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# vi:si:et:sw=4:sts=4:ts=4
|
|
|
|
import os
|
|
|
|
import mimetypes
|
2011-08-19 18:08:02 +00:00
|
|
|
from datetime import datetime, timedelta
|
2010-11-23 09:23:40 +00:00
|
|
|
|
|
|
|
from django.http import HttpResponse, Http404
|
|
|
|
from django.conf import settings
|
|
|
|
|
|
|
|
|
|
|
|
def HttpFileResponse(path, content_type=None, filename=None):
|
|
|
|
if not os.path.exists(path):
|
|
|
|
raise Http404
|
|
|
|
if not content_type:
|
|
|
|
content_type = mimetypes.guess_type(path)[0]
|
2011-10-21 16:44:45 +00:00
|
|
|
if not content_type:
|
|
|
|
content_type = 'application/octet-stream'
|
|
|
|
|
2011-04-06 18:38:00 +00:00
|
|
|
if getattr(settings, 'XACCELREDIRECT', False):
|
2010-11-23 09:23:40 +00:00
|
|
|
response = HttpResponse()
|
|
|
|
response['Content-Length'] = os.stat(path).st_size
|
2011-04-06 18:38:00 +00:00
|
|
|
|
|
|
|
for PREFIX in ('STATIC', 'MEDIA'):
|
|
|
|
root = getattr(settings, PREFIX+'_ROOT', '')
|
|
|
|
url = getattr(settings, PREFIX+'_URL', '')
|
|
|
|
if root and path.startswith(root):
|
|
|
|
path = url + path[len(root)+1:]
|
2010-11-23 09:23:40 +00:00
|
|
|
response['X-Accel-Redirect'] = path
|
2011-10-21 16:37:51 +00:00
|
|
|
if content_type:
|
|
|
|
response['Content-Type'] = content_type
|
2011-04-06 18:38:00 +00:00
|
|
|
elif getattr(settings, 'XSENDFILE', False):
|
2010-11-23 09:23:40 +00:00
|
|
|
response = HttpResponse()
|
|
|
|
response['X-Sendfile'] = path
|
2011-10-21 16:37:51 +00:00
|
|
|
if content_type:
|
|
|
|
response['Content-Type'] = content_type
|
2010-11-23 09:23:40 +00:00
|
|
|
response['Content-Length'] = os.stat(path).st_size
|
|
|
|
else:
|
|
|
|
response = HttpResponse(open(path), content_type=content_type)
|
|
|
|
if filename:
|
2011-08-19 18:08:02 +00:00
|
|
|
response['Content-Disposition'] = 'attachment; filename="%s"' % filename
|
|
|
|
response['Expires'] = datetime.strftime(datetime.utcnow() + timedelta(days=1), "%a, %d-%b-%Y %H:%M:%S GMT")
|
2010-11-23 09:23:40 +00:00
|
|
|
return response
|
|
|
|
|