Overview, concepts¶
Given:
- you manage files with Django (permissions, filters, generation, ...)
- files are stored somewhere or generated somehow (local filesystem, remote storage, memory...)
As a developer, you want to serve files quick and efficiently.
Here is an overview of django-downloadview‘s answer...
Generic views cover commons patterns¶
Choose the generic view depending on the file you want to serve:
- ObjectDownloadView: file field in a model;
- StorageDownloadView: file in a storage;
- PathDownloadView: absolute filename on local filesystem;
- HTTPDownloadView: file at URL (the resource is proxied);
- VirtualDownloadView: bytes, text, file-like objects, generated files...
Generic views and mixins allow easy customization¶
If your use case is a bit specific, you can easily extend the views above or create your own based on mixins.
Views return DownloadResponse¶
Views return DownloadResponse
. It is
a special django.http.StreamingHttpResponse
where content is
encapsulated in a file wrapper.
Learn more in Responses.
DownloadResponse carry file wrapper¶
Views instanciate a file wrapper and use it to initialize responses.
File wrappers describe files: they carry files properties such as name, size, encoding...
File wrappers implement loading and iterating over file content. Whenever possible, file wrappers do not embed file data, in order to save memory.
Learn more about available file wrappers in File wrappers.
Middlewares convert DownloadResponse into ProxiedDownloadResponse¶
Before WSGI application use file wrapper and actually use file contents,
middlewares or decorators) are given the opportunity to capture
DownloadResponse
instances.
Let’s take this opportunity to optimize file loading and streaming!
A good optimization it to delegate streaming to a reverse proxy, such as nginx [1] via X-Accel [2] internal redirects. This way, Django doesn’t load file content in memory.
django_downloadview provides middlewares that convert
DownloadResponse
into
ProxiedDownloadResponse
.
Learn more in Optimize streaming.
Testing matters¶
django-downloadview also helps you test the views you customized.
You may also write healthchecks to make sure everything goes fine in live environments.
What’s next?¶
Let’s install django-downloadview.
Notes & references
[1] | http://nginx.org |
[2] | http://wiki.nginx.org/X-accel |