You should use sendfile apis given by popular servers like apache
or nginx
in production. For many years I was using the sendfile api of these servers for protecting files. Then created a simple middleware based django app for this purpose suitable for both development & production purposes. You can access the source code here.
UPDATE: in new version python
provider uses django FileResponse
if available and also adds support for many server implementations from lighthttp, caddy to hiawatha
Usage
pip install django-fileprovider
- add
fileprovider
app to INSTALLED_APPS
settings,
- add
fileprovider.middleware.FileProviderMiddleware
to MIDDLEWARE_CLASSES
settings
- set
FILEPROVIDER_NAME
settings to nginx
or apache
in production, by default it is python
for development purpose.
in your class-based or function views, set the response header X-File
value to the absolute path of the file. For example:
def hello(request):
# code to check or protect the file from unauthorized access
response = HttpResponse()
response['X-File'] = '/absolute/path/to/file'
return response
django-fileprovider
implemented 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
location /files/ {
internal;
root /home/sideffect0/secret_files/;
}
Here nginx
sets a location url /files/
only access internaly, if you are using above configuration you can set X-File
as:
response['X-File'] = '/files/filename.extension'
By doing this with nginx configuration, the file will be protected & also you can control the file from django views