I've been using a method for serving downloads but since it was not secure i decided to change that . ( the method was a link to the original file in storage , but the risk was that everyone with the link could have downloaded the file ! ) so i now serve the file via my views , that way only users with permission can download the file , but i'm noticing a high load on server while there is many simultaneous download requests for the files. here's part of my code that handles downloads for users ( Consider the file is an image )
image = Image.open ("the path to file")
response = HttpResponse(mimetype = 'image/png' )
response['Content-Disposition'] = 'attachment: filename=%s.png' % filename
image.save(response , "png")
return response
is there any better ways for serving files while keeping the security and lowering server side load ? thanks in advance :)
Your opening of the image loads it in memory and this is what causes the increase in load under heavy use. As posted by Martin the real solution is to serve the file directly.
Here is another approach, which will stream your file in chunks without loading it in memory.
FileWrapper won't work when GZipMiddleware is installed (Django 1.4 and below): https://code.djangoproject.com/ticket/6027
If using GZipMiddleware, a practical solution is to write a subclass of FileWrapper like so:
As of Python 2.5, there's no need to import FileWrapper from Django.
Unless you are going to be serving very very small number of such requests, any solution that requires serving your content via django won't be scalable. For anything to scale in future, you'll probably want to move your content storage and serving to to a separate server and then this won't work.
The recommended way would be to keep static content served through a lighter server (such as nginx). To add security, pass the static server a token from django by setting the cookie or via the get parameters.
The token should have following values: timestamp, filename, userid. It should be signed via some key by the django app.
Next, write a small nginx module which checks the token and that the user has indeed access to the file. It should also check that token isn't old enough by checking the timestamp.
It's better to use FileRespose, is a subclass of StreamingHttpResponse optimized for binary files. It uses wsgi.file_wrapper if provided by the wsgi server, otherwise it streams the file out in small chunks.
You can use the 'sendfile' method as described in this answer.
Practically you need this (c&p):
This requires mod_xsendfile (which is also supported by nginx or lighty)