Fixed #16470 -- Allowed FileResponse to auto-set some Content headers.

Thanks Simon Charette, Jon Dufresne, and Tim Graham for the reviews.
This commit is contained in:
Claude Paroz 2018-05-15 18:12:11 +02:00 committed by GitHub
parent 2dcc5d629a
commit a177f854c3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 192 additions and 82 deletions

View file

@ -1054,17 +1054,45 @@ Attributes
``FileResponse`` objects
========================
.. class:: FileResponse
.. class:: FileResponse(open_file, as_attachment=False, filename='', **kwargs)
:class:`FileResponse` is a subclass of :class:`StreamingHttpResponse` optimized
for binary files. It uses `wsgi.file_wrapper`_ if provided by the wsgi server,
otherwise it streams the file out in small chunks.
:class:`FileResponse` is a subclass of :class:`StreamingHttpResponse`
optimized for binary files. It uses `wsgi.file_wrapper`_ if provided by the
wsgi server, otherwise it streams the file out in small chunks.
If ``as_attachment=True``, the ``Content-Disposition`` header is set, which
asks the browser to offer the file to the user as a download.
If ``open_file`` doesn't have a name or if the name of ``open_file`` isn't
appropriate, provide a custom file name using the ``filename`` parameter.
The ``Content-Length``, ``Content-Type``, and ``Content-Disposition``
headers are automatically set when they can be guessed from contents of
``open_file``.
.. versionadded:: 2.1
The ``as_attachment`` and ``filename`` keywords argument were added.
Also, ``FileResponse`` sets the ``Content`` headers if it can guess
them.
.. _wsgi.file_wrapper: https://www.python.org/dev/peps/pep-3333/#optional-platform-specific-file-handling
``FileResponse`` expects a file open in binary mode like so::
``FileResponse`` accepts any file-like object with binary content, for example
a file open in binary mode like so::
>>> from django.http import FileResponse
>>> response = FileResponse(open('myfile.png', 'rb'))
The file will be closed automatically, so don't open it with a context manager.
Methods
-------
.. method:: FileResponse.set_headers(open_file)
.. versionadded:: 2.1
This method is automatically called during the response initialization and
set various headers (``Content-Length``, ``Content-Type``, and
``Content-Disposition``) depending on ``open_file``.