- Author:
- eternicode
- Posted:
- May 2, 2012
- Language:
- Python
- Version:
- 1.3
- Score:
- 1 (after 1 ratings)
An HttpResponse for giving the user a file download, taking advantage of X-Sendfile if it's available, using FileWrapper if not.
Usage:
HttpResponseSendfile('/path/to/file.ext')
To bypass the fallback:
HttpResponseSendfile('/path/to/file.ext', fallback=False)
This has been tested working with Lighttpd 1.4.28's mod_fastcgi.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Note that there is also django-sendfile which also supports nginx's X-Accel-Redirect and more.
#
Had problem with X-Sendfile line, because path can have non-us chars. Fixed by adding encoding: self['X-Sendfile'] = path.encode('utf8')
#
Please login first before commenting.