django_downloadview Package

django_downloadview Package

django-downloadview provides generic download views for Django.

decorators Module

View decorators.

See also decorators provided by server-specific modules, such as django_downloadview.nginx.x_accel_redirect().

class django_downloadview.decorators.DownloadDecorator(middleware_factory)

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.

files Module

File wrappers for use as exchange data between views and responses.

class django_downloadview.files.HTTPFile(request_factory=<function get at 0x2dcaf50>, url='', name=u'', **kwargs)

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.

file
request
size

Return the total size, in bytes, of the file.

Reads response’s “content-length” header.

class django_downloadview.files.StorageFile(storage, name, file=None)

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.

accessed_time

Return the last accessed time (as datetime object) of the file.

Proxy to self.storage.accessed_time(self.name).

created_time

Return the creation time (as datetime object) of the file.

Proxy to self.storage.created_time(self.name).

delete()

Delete the specified file from the storage system.

Proxy to self.storage.delete(self.name).

exists()

Return True if file already exists in the storage system.

If False, then the name is available for a new file.

file

Required by django.core.files.utils.FileProxy.

modified_time

Return the last modification time (as datetime object) of the file.

Proxy to self.storage.modified_time(self.name).

open(mode='rb')

Retrieves the specified file from storage and return open() result.

Proxy to self.storage.open(self.name, mode).

path

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

save(content)

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.

size

Return the total size, in bytes, of the file.

Proxy to self.storage.size(self.name).

url

Return an absolute URL where the file’s contents can be accessed.

Proxy to self.storage.url(self.name).

class django_downloadview.files.VirtualFile(file=None, name=u'', url='', size=None)

Bases: django.core.files.base.File

Wrapper for files that live in memory.

size

middlewares Module

Base material for download middlewares.

class django_downloadview.middlewares.BaseDownloadMiddleware

Bases: object

Base (abstract) Django middleware that handles download responses.

Subclasses must implement process_download_response() method.

is_download_response(response)

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.

process_download_response(request, response)

Handle file download response.

process_response(request, response)

Call process_download_response() if response is download.

nginx Module

Optimizations for Nginx.

See also Nginx X-accel documentation and narrative documentation about Nginx optimizations.

class django_downloadview.nginx.BaseXAccelRedirectMiddleware(source_dir=None, source_url=None, destination_url=None, expires=None, with_buffering=None, limit_rate=None, media_root=None, media_url=None)

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.

get_redirect_url(response)

Return redirect URL for file wrapped into response.

is_download_response(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.

process_download_response(request, response)

Replace DownloadResponse instances by NginxDownloadResponse ones.

django_downloadview.nginx.DEFAULT_DESTINATION_URL = None

Default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_DESTINATION_URL.

django_downloadview.nginx.DEFAULT_EXPIRES = None

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.

django_downloadview.nginx.DEFAULT_LIMIT_RATE = None

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.

django_downloadview.nginx.DEFAULT_SOURCE_DIR = ''

Default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_DIR.

django_downloadview.nginx.DEFAULT_SOURCE_URL = ''

Default value for settings.NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_URL.

django_downloadview.nginx.DEFAULT_WITH_BUFFERING = None

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.

class django_downloadview.nginx.XAccelRedirectMiddleware

Bases: django_downloadview.nginx.BaseXAccelRedirectMiddleware

Apply X-Accel-Redirect globally, via Django settings.

Available settings are:

NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_URL:
The string at the beginning of URLs to replace with NGINX_DOWNLOAD_MIDDLEWARE_DESTINATION_URL. If None, then URLs aren’t captured. Defaults to settings.MEDIA_URL.
NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_DIR:
The string at the beginning of filenames (path) to replace with NGINX_DOWNLOAD_MIDDLEWARE_DESTINATION_URL. If None, then filenames aren’t captured. Defaults to settings.MEDIA_ROOT.
NGINX_DOWNLOAD_MIDDLEWARE_DESTINATION_URL:
The base URL where requests are proxied to. If None an ImproperlyConfigured exception is raised.

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.

NGINX_DOWNLOAD_MIDDLEWARE_MEDIA_ROOT:
Replaced by NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_DIR.
NGINX_DOWNLOAD_MIDDLEWARE_MEDIA_URL:
Replaced by NGINX_DOWNLOAD_MIDDLEWARE_DESTINATION_URL.
class django_downloadview.nginx.XAccelRedirectResponse(redirect_url, content_type, basename=None, expires=None, with_buffering=None, limit_rate=None)

Bases: django.http.response.HttpResponse

Http response that delegates serving file to Nginx.

class django_downloadview.nginx.XAccelRedirectValidator

Bases: object

Utility class to validate XAccelRedirectResponse instances.

See also assert_x_accel_redirect() shortcut function.

assert_basename(test_case, response, value)
assert_charset(test_case, response, value)
assert_content_type(test_case, response, value)
assert_expires(test_case, response, value)
assert_limit_rate(test_case, response, value)
assert_redirect_url(test_case, response, value)
assert_with_buffering(test_case, response, value)
assert_x_accel_redirect_response(test_case, response)
django_downloadview.nginx.assert_x_accel_redirect(test_case, response, **assertions)

Make test_case assert that response is a XAccelRedirectResponse.

Optional assertions dictionary can be used to check additional items:

  • basename: the basename of the file in the response.
  • content_type: the value of “Content-Type” header.
  • redirect_url: the value of “X-Accel-Redirect” header.
  • charset: the value of X-Accel-Charset header.
  • with_buffering: the value of X-Accel-Buffering header. If False, then makes sure that the header disables buffering. If None, then makes sure that the header is not set.
  • expires: the value of X-Accel-Expires header. If False, then makes sure that the header disables expiration. If None, then makes sure that the header is not set.
  • limit_rate: the value of X-Accel-Limit-Rate header. If False, then makes sure that the header disables limit rate. If None, then makes sure that the header is not set.
django_downloadview.nginx.x_accel_redirect = <django_downloadview.decorators.DownloadDecorator object at 0x304e590>

Apply BaseXAccelRedirectMiddleware to view_func response.

Proxies additional arguments (*args, **kwargs) to BaseXAccelRedirectMiddleware constructor (expires, with_buffering, and limit_rate).

response Module

HttpResponse subclasses.

class django_downloadview.response.DownloadResponse(file_instance, attachment=True, basename=None, status=200, content_type=None)

Bases: django.http.response.StreamingHttpResponse

File download response.

content attribute is supposed to be a file object wrapper, which makes this response “lazy”.

default_headers

Return dictionary of automatically-computed headers.

Uses an internal _default_headers cache. Default values are computed if only cache hasn’t been set.

get_basename()

Return basename.

get_charset()

Return the charset of the file to serve.

get_content_type()

Return a suitable “Content-Type” header for self.file.

get_encoding()

Return encoding of the file to serve.

get_mime_type()

Return mime-type of the file.

items()

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! :’(

django_downloadview.response.is_download_response(response)

Return True if response is a download response.

Current implementation returns True if response is an instance of django_downloadview.response.DownloadResponse.

test Module

Testing utilities.

class django_downloadview.test.DownloadResponseValidator

Bases: object

Utility class to validate DownloadResponse instances.

assert_attachment(test_case, response, value)
assert_basename(test_case, response, value)
assert_content(test_case, response, value)
assert_content_type(test_case, response, value)
assert_download_response(test_case, response)
assert_mime_type(test_case, response, value)
django_downloadview.test.assert_download_response(test_case, response, **assertions)

Make test_case assert that response is a DownloadResponse.

Optional assertions dictionary can be used to check additional items:

  • basename: the basename of the file in the response.
  • content_type: the value of “Content-Type” header.
  • charset: the value of X-Accel-Charset header.
  • content: the content of the file to be downloaded.
class django_downloadview.test.temporary_media_root(**kwargs)

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
disable()

Remove directory settings.MEDIA_ROOT then restore original setting.

enable()

Create a temporary directory and use it to override settings.MEDIA_ROOT.

utils Module

Utility functions.

django_downloadview.utils.content_type_to_charset(content_type)

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 Module

Views.

class django_downloadview.views.BaseDownloadView(**kwargs)

Bases: django_downloadview.views.DownloadMixin, django.views.generic.base.View

get(request, *args, **kwargs)

Handle GET requests: stream a file.

class django_downloadview.views.DownloadMixin

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.

attachment = True

Whether to return the response as attachment or not.

basename = None

Client-side filename, if only file is returned as attachment.

get_basename()
get_file()

Return a file wrapper instance.

render_to_response(*args, **kwargs)

Returns a response with a file as attachment.

response_class

Response class to be used in render_to_response().

alias of DownloadResponse

class django_downloadview.views.HTTPDownloadView(**kwargs)

Bases: django_downloadview.views.BaseDownloadView

Proxy files that live on remote servers.

get_file()

Return wrapper which has an url attribute.

get_request_factory()

Return request factory to perform actual HTTP request.

get_request_kwargs()

Return keyword arguments for use with request factory.

get_url()

Return remote file URL (the one we are proxying).

request_kwargs = {}

Additional keyword arguments for request handler.

url = u''

URL to download (the one we are proxying).

class django_downloadview.views.ObjectDownloadView(**kwargs)

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.

basename_field = None

Optional name of the model’s attribute which contains the basename.

charset_field = None

Optional name of the model’s attribute which contains the charset.

encoding_field = None

Optional name of the model’s attribute which contains the encoding.

file_field = 'file'

Name of the model’s attribute which contains the file to be streamed. Typically the name of a FileField.

get_basename()

Return client-side filename.

get_file()

Return FieldFile instance.

mime_type_field = None

Optional name of the model’s attribute which contains the MIME type.

modification_time_field = None

Optional name of the model’s attribute which contains the modification

size_field = None

Optional name of the model’s attribute which contains the size.

class django_downloadview.views.PathDownloadView(**kwargs)

Bases: django_downloadview.views.BaseDownloadView

Serve a file using filename.

get_file()

Use path to return wrapper around file to serve.

get_path()

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.

path = None

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.

path_url_kwarg = 'path'

Name of the URL argument that contains path.

class django_downloadview.views.StorageDownloadView(**kwargs)

Bases: django_downloadview.views.PathDownloadView

Serve a file using storage and filename.

get_file()

Use path and storage to return wrapper around file to serve.

get_path()

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 = None

Path to the file to serve relative to storage.

storage = <django.core.files.storage.DefaultStorage object at 0x2dd2310>

Storage the file to serve belongs to.

class django_downloadview.views.VirtualDownloadView(**kwargs)

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.

get_file()

Return wrapper.

Table Of Contents

Previous topic

django_downloadview

Next topic

About django-downloadview

This Page