I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.
For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt
And on the server, I know that all downloadable files reside in a folder "/home/user/files/".
Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?
I have faced the same problem more then once and so implemented using xsendfile module and auth view decorators the django-filelibrary. Feel free to use it as inspiration for your own solution.
https://github.com/danielsokolowski/django-filelibrary
You should use sendfile apis given by popular servers like
apache
ornginx
in production. Many years i was using sendfile api of these servers for protecting files. Then created a simple middleware based django app for this purpose suitable for both development & production purpose.You can access the source code here.UPDATE: in new version
python
provider uses djangoFileResponse
if available and also adds support for many server implementations from lighthttp, caddy to hiawathaUsage
fileprovider
app toINSTALLED_APPS
settings,fileprovider.middleware.FileProviderMiddleware
toMIDDLEWARE_CLASSES
settingsFILEPROVIDER_NAME
settings tonginx
orapache
in production, by default it ispython
for development purpose.in your classbased or function views set response header
X-File
value to absolute path to the file. For example,django-fileprovider
impemented in a way that your code will need only minimum modification.Nginx configuration
To protect file from direct access you can set the configuration as
Here
nginx
sets a location url/files/
only access internaly, if you are using above configuration you can set X-File as,By doing this with nginx configuration, the file will be protected & also you can control the file from django
views