views:

202

answers:

2

From my Django application I want to serve up secure photos. The photos are not for public consumption, I only want logged in users to have the ability to view them. I don't want to rely on obfuscated file id's (giving a photo a UUID of a long number) and count on that being hidden in my media folder. How would I store a photo securely on disk in my database and only stream it out to an authenticated session?

+1  A: 

You can do this by creating a HttpResponse with the mime type of the image and then writes/copies the image file to it.

A simple version could look like the following:

from django.http import HttpResponse

@your_favourite_permission_decorator
def image(request):
    response = HttpResponse(mimetype='image/png')

    with open("image.png") as img:
        response.write(img.read())
    return response

Also, see this example for PDF files and this example with PIL.

Debilski
+1  A: 

Use X-Sendfile headers to tell your front end server what file to actually server.

@check_permissions
def image(request):
    response = HttpResponse(mimetype='image/png')    
    response['X-Sendfile'] = "/real/path/to/image.png"
    return response

Here is a related question. You can also see a real world implementation by looking at how Satchmo serves DownloadableProduct objects.

One final note, nginx and lighttpd use X-Accel-Redirect and X-LIGHTTPD-send-file instead of X-Sendfile.

istruble
That does not seem to work with the built-in server. Is that correct or am I doing something wrong?
Debilski