Login

HttpResponseSendfile

Author:
eternicode
Posted:
May 2, 2012
Language:
Python
Version:
1.3
Tags:
download sendfile x-sendfile
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

  1. Multiple cache backend by isaidyep 4 years, 10 months ago
  2. X-Sendfile static file serve view by dokterbob 4 years, 9 months ago
  3. Query lookups using operators by diverman 4 years, 12 months ago
  4. Single Django App behind multiple Apache Proxies by chadmaine 8 years, 3 months ago
  5. whitespaceoptimize block tag by peterbe 6 years, 10 months ago

Comments

arthur (on May 3, 2012):

Note that there is also django-sendfile which also supports nginx's X-Accel-Redirect and more.

#

Mika (on September 12, 2013):

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.