Django: Password protect photo url's?
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 t开发者_开发问答hem. 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?
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.
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.
If it was Apache server with mod_python, this could potentially be an interesting article about Apache using Django's authentication system.
精彩评论