django-downloadview provides generic download views for Django.
View decorators.
See also decorators provided by server-specific modules, such as django_downloadview.nginx.x_accel_redirect().
Bases: object
View decorator factory to apply middleware to view_func response.
Middleware instance is built from middleware_factory with *args and **kwargs. Middleware factory is typically a class, such as some django_downloadview.middlewares.XAccelMiddleware subclass.
Response is built from view, then the middleware’s process_response method is applied on response.
File wrappers for use as exchange data between views and responses.
Bases: django.core.files.base.File
Wrapper for files that live on remote HTTP servers.
Acts as a proxy.
Uses https://pypi.python.org/pypi/requests.
Always sets “stream=True” in requests kwargs.
Return the total size, in bytes, of the file.
Reads response’s “content-length” header.
Bases: django.core.files.base.File
A file in a Django storage.
This class looks like django.db.models.fields.files.FieldFile, but unrelated to model instance.
Return the last accessed time (as datetime object) of the file.
Proxy to self.storage.accessed_time(self.name).
Return the creation time (as datetime object) of the file.
Proxy to self.storage.created_time(self.name).
Delete the specified file from the storage system.
Proxy to self.storage.delete(self.name).
Return True if file already exists in the storage system.
If False, then the name is available for a new file.
Required by django.core.files.utils.FileProxy.
Return the last modification time (as datetime object) of the file.
Proxy to self.storage.modified_time(self.name).
Retrieves the specified file from storage and return open() result.
Proxy to self.storage.open(self.name, mode).
Return a local filesystem path which is suitable for open().
Proxy to self.storage.path(self.name).
May raise NotImplementedError if storage doesn’t support file access with Python’s built-in open() function
Saves new content to the file.
Proxy to self.storage.save(self.name).
The content should be a proper File object, ready to be read from the beginning.
Return the total size, in bytes, of the file.
Proxy to self.storage.size(self.name).
Return an absolute URL where the file’s contents can be accessed.
Proxy to self.storage.url(self.name).
Base material for download middlewares.
Bases: object
Base (abstract) Django middleware that handles download responses.
Subclasses must implement process_download_response() method.
Return True if response can be considered as a file download.
By default, this method uses django_downloadview.response.is_download_response(). Override this method if you want a different behaviour.
Handle file download response.
Call process_download_response() if response is download.
Optimizations for Nginx.
See also Nginx X-accel documentation and narrative documentation about Nginx optimizations.
Bases: django_downloadview.middlewares.BaseDownloadMiddleware
Configurable middleware, for use in decorators or in global middlewares.
Standard Django middlewares are configured globally via settings. Instances of this class are to be configured individually. It makes it possible to use this class as the factory in django_downloadview.decorators.DownloadDecorator.
Return redirect URL for file wrapped into response.
Return True for DownloadResponse, except for “virtual” files.
This implementation can’t handle files that live in memory or which are to be dynamically iterated over. So, we capture only responses whose file attribute have either an URL or a file name.
Replace DownloadResponse instances by NginxDownloadResponse ones.
Default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_DESTINATION_URL.
Default value for X-Accel-Limit-Expires header. Also default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_EXPIRES.
See http://wiki.nginx.org/X-accel#X-Accel-Limit-Expires
Default value is None, which means “let Nginx choose”, i.e. use Nginx defaults or specific configuration.
If set to False, Nginx buffering is disabled. Else, it indicates the expiration delay, in seconds.
Default value for X-Accel-Limit-Rate header. Also default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_LIMIT_RATE.
See http://wiki.nginx.org/X-accel#X-Accel-Limit-Rate
Default value is None, which means “let Nginx choose”, i.e. use Nginx defaults or specific configuration.
If set to False, Nginx limit rate is disabled. Else, it indicates the limit rate in bytes.
Default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_DIR.
Default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_URL.
Default value for X-Accel-Buffering header. Also default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_WITH_BUFFERING.
See http://wiki.nginx.org/X-accel#X-Accel-Limit-Buffering
Default value is None, which means “let Nginx choose”, i.e. use Nginx defaults or specific configuration.
If set to False, Nginx buffering is disabled. If set to True, Nginx buffering is enabled.
Bases: django_downloadview.nginx.BaseXAccelRedirectMiddleware
Apply X-Accel-Redirect globally, via Django settings.
Available settings are:
Note
The following settings are deprecated since version 1.1. URLs can be used as redirection source since 1.1, and then “MEDIA_ROOT” and “MEDIA_URL” became too confuse.
Bases: django.http.response.HttpResponse
Http response that delegates serving file to Nginx.
Bases: object
Utility class to validate XAccelRedirectResponse instances.
See also assert_x_accel_redirect() shortcut function.
Make test_case assert that response is a XAccelRedirectResponse.
Optional assertions dictionary can be used to check additional items:
Apply BaseXAccelRedirectMiddleware to view_func response.
Proxies additional arguments (*args, **kwargs) to BaseXAccelRedirectMiddleware constructor (expires, with_buffering, and limit_rate).
HttpResponse subclasses.
Bases: django.http.response.StreamingHttpResponse
File download response.
content attribute is supposed to be a file object wrapper, which makes this response “lazy”.
Return dictionary of automatically-computed headers.
Uses an internal _default_headers cache. Default values are computed if only cache hasn’t been set.
Return basename.
Return the charset of the file to serve.
Return a suitable “Content-Type” header for self.file.
Return encoding of the file to serve.
Return mime-type of the file.
Return iterable of (header, value).
This method is called by http handlers just before WSGI’s start_response() is called... but it is not called by django.test.ClientHandler! :’(
Return True if response is a download response.
Current implementation returns True if response is an instance of django_downloadview.response.DownloadResponse.
Testing utilities.
Bases: object
Utility class to validate DownloadResponse instances.
Make test_case assert that response is a DownloadResponse.
Optional assertions dictionary can be used to check additional items:
Bases: django.test.utils.override_settings
Context manager or decorator to override settings.MEDIA_ROOT.
>>> from django_downloadview.test import temporary_media_root
>>> from django.conf import settings
>>> global_media_root = settings.MEDIA_ROOT
>>> with temporary_media_root():
... global_media_root == settings.MEDIA_ROOT
False
>>> global_media_root == settings.MEDIA_ROOT
True
>>> @temporary_media_root()
... def use_temporary_media_root():
... return settings.MEDIA_ROOT
>>> tmp_media_root = use_temporary_media_root()
>>> global_media_root == tmp_media_root
False
>>> global_media_root == settings.MEDIA_ROOT
True
Remove directory settings.MEDIA_ROOT then restore original setting.
Create a temporary directory and use it to override settings.MEDIA_ROOT.
Utility functions.
Return charset part of content-type header.
>>> from django_downloadview.utils import content_type_to_charset
>>> content_type_to_charset('text/html; charset=utf-8')
'utf-8'
Views.
Bases: django_downloadview.views.DownloadMixin, django.views.generic.base.View
Handle GET requests: stream a file.
Bases: object
Placeholders and base implementation to create file download views.
The get_file() method is a placeholder, which raises NotImplementedError in base implementation.
The other methods provide an implementation that use the file object returned by get_file(), supposing the file is hosted on the local filesystem.
You may override one or several methods to adapt the implementation to your use case.
Whether to return the response as attachment or not.
Client-side filename, if only file is returned as attachment.
Return a file wrapper instance.
Returns a response with a file as attachment.
Response class to be used in render_to_response().
alias of DownloadResponse
Bases: django_downloadview.views.BaseDownloadView
Proxy files that live on remote servers.
Return wrapper which has an url attribute.
Return request factory to perform actual HTTP request.
Return keyword arguments for use with request factory.
Return remote file URL (the one we are proxying).
Additional keyword arguments for request handler.
URL to download (the one we are proxying).
Bases: django_downloadview.views.DownloadMixin, django.views.generic.detail.BaseDetailView
Download view for models which contain a FileField.
This class extends BaseDetailView, so you can use its arguments to target the instance to operate on: slug, slug_kwarg, model, queryset... See Django’s DetailView reference for details.
In addition to BaseDetailView arguments, you can set arguments related to the file to be downloaded.
The main one is file_field.
The other arguments are provided for convenience, in case your model holds some (deserialized) metadata about the file, such as its basename, its modification time, its MIME type... These fields may be particularly handy if your file storage is not the local filesystem.
Optional name of the model’s attribute which contains the basename.
Optional name of the model’s attribute which contains the charset.
Optional name of the model’s attribute which contains the encoding.
Name of the model’s attribute which contains the file to be streamed. Typically the name of a FileField.
Return client-side filename.
Return FieldFile instance.
Optional name of the model’s attribute which contains the MIME type.
Optional name of the model’s attribute which contains the modification
Optional name of the model’s attribute which contains the size.
Bases: django_downloadview.views.BaseDownloadView
Serve a file using filename.
Use path to return wrapper around file to serve.
Return actual path of the file to serve.
Default implementation simply returns view’s path.
Override this method if you want custom implementation. As an example, path could be relative and your custom get_path() implementation makes it absolute.
Server-side name (including path) of the file to serve.
Filename is supposed to be an absolute filename of a file located on the local filesystem.
Name of the URL argument that contains path.
Bases: django_downloadview.views.PathDownloadView
Serve a file using storage and filename.
Use path and storage to return wrapper around file to serve.
Return path of the file to serve, relative to storage.
Default implementation simply returns view’s path.
Override this method if you want custom implementation.
Path to the file to serve relative to storage.
Storage the file to serve belongs to.
Bases: django_downloadview.views.BaseDownloadView
Serve not-on-disk or generated-on-the-fly file.
Use this class to serve StringIO files.
Override the get_file() method to customize file wrapper.
Return wrapper.