Fixed #35631 -- Added HttpRequest.get_preferred_type().

This commit is contained in:
Jake Howard 2024-07-26 12:34:42 +01:00 committed by Sarah Boyce
parent 826ef00668
commit e161bd4657
5 changed files with 247 additions and 26 deletions

View file

@ -425,10 +425,48 @@ Methods
Returns ``True`` if the request is secure; that is, if it was made with
HTTPS.
.. method:: HttpRequest.get_preferred_type(media_types)
.. versionadded:: 5.2
Returns the preferred mime type from ``media_types``, based on the
``Accept`` header, or ``None`` if the client does not accept any of the
provided types.
Assuming the client sends an ``Accept`` header of
``text/html,application/json;q=0.8``:
.. code-block:: pycon
>>> request.get_preferred_type(["text/html", "application/json"])
"text/html"
>>> request.get_preferred_type(["application/json", "text/plain"])
"application/json"
>>> request.get_preferred_type(["application/xml", "text/plain"])
None
Most browsers send ``Accept: */*`` by default, meaning they don't have a
preference, in which case the first item in ``media_types`` would be
returned.
Setting an explicit ``Accept`` header in API requests can be useful for
returning a different content type for those consumers only. See
:ref:`content-negotiation-example` for an example of returning
different content based on the ``Accept`` header.
.. note::
If a response varies depending on the content of the ``Accept`` header
and you are using some form of caching like Django's
:mod:`cache middleware <django.middleware.cache>`, you should decorate
the view with :func:`vary_on_headers('Accept')
<django.views.decorators.vary.vary_on_headers>` so that the responses
are properly cached.
.. method:: HttpRequest.accepts(mime_type)
Returns ``True`` if the request ``Accept`` header matches the ``mime_type``
argument:
Returns ``True`` if the request's ``Accept`` header matches the
``mime_type`` argument:
.. code-block:: pycon
@ -436,17 +474,10 @@ Methods
True
Most browsers send ``Accept: */*`` by default, so this would return
``True`` for all content types. Setting an explicit ``Accept`` header in
API requests can be useful for returning a different content type for those
consumers only. See :ref:`content-negotiation-example` of using
``accepts()`` to return different content to API consumers.
``True`` for all content types.
If a response varies depending on the content of the ``Accept`` header and
you are using some form of caching like Django's :mod:`cache middleware
<django.middleware.cache>`, you should decorate the view with
:func:`vary_on_headers('Accept')
<django.views.decorators.vary.vary_on_headers>` so that the responses are
properly cached.
See :ref:`content-negotiation-example` for an example of using
``accepts()`` to return different content based on the ``Accept`` header.
.. method:: HttpRequest.read(size=None)
.. method:: HttpRequest.readline()