[Fixed]-How to make a private download area with django?

11👍

So, searching I found this discussion thread.

There were three things said you might be interested in.

First there is the mod_python method
Then there is the mod_wsgi method

Both of which don’t seem all that great.

Better is the X-Sendfile header which isn’t fully standard, but works at least within apache, and lighttpd.

kibbitzing from here, we have the following.

@login_required
def serve_file(request, context):
    if <check if they have access to the file>:
        filename = "/var/www/myfile.xyz" 
        response = HttpResponse(mimetype='application/force-download') 
        response['Content-Disposition']='attachment;filename="%s"'%filename
        response["X-Sendfile"] = filename
        response['Content-length'] = os.stat("debug.py").st_size
        return response
    return <error state>

and that should be almost exactly what you want. Just make sure you turn on X-Sendfile support in whatever you happen to be using.

👤emeryc

3👍

The XSendfile seems to be the right approach but It looks to be a bit complex to setup. I’ve decided to use a simpler way.

Based on emeryc answer and django snippets http://www.djangosnippets.org/snippets/365/, I have written the following code and it seems to make what I want:

@login_required
def serve_file(request, filename):
    fullname = myapp.settings.PRIVATE_AREA+filename
    try:
        f = file(fullname, "rb")
    except Exception, e:
        return page_not_found(request, template_name='404.html')
    try:
        wrapper = FileWrapper(f)
        response = HttpResponse(wrapper, mimetype=mimetypes.guess_type(filename)[0])
        response['Content-Length'] = os.path.getsize(fullname)
        response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
        return response
    except Exception, e:
        return page_not_found(request, template_name='500.html')
👤luc

1👍

There’s tons of tutorials on how to enable authentication in Django. Do you need help with that? If so, start here.

The next step is to create a View which lists your files. So do that, this is all basic Django. If you have problems with this step, go back and go through the Django tutorial. You’ll get this.

Finally, refer back to the first link (here is is again: authentication docs) and take a close look at the LOGIN_REQUIRED decorator. Protect your view with this decorator.

This is all pretty basic Django stuff. If you’ve done this and have a specific question, post it here. But you put a pretty open ended question on SO and that’s not a great way to get assistance.

👤marcc

Leave a comment