HttpResponseSendfile

 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. X-Sendfile static file serve view by dokterbob 2 years, 8 months ago
  2. Apache X-sendfile with permissions checking by h0axify 1 year, 2 months ago
  3. Simple FastCGI authorizer view by cme 4 years, 7 months ago
  4. another render_to_response wrapper by ro60 5 years, 5 months ago
  5. send_file and send_data by danjak 6 years, 3 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.

#

(Forgotten your password?)