Debian Codegraph @

docs/ref/request-response.txt

raw
1 ============================
2 Request and response objects
3 ============================
4
5 .. module:: django.http
6 :synopsis: Classes dealing with HTTP requests and responses.
7
8 Quick overview
9 ==============
10
11 Django uses request and response objects to pass state through the system.
12
13 When a page is requested, Django creates an :class:`HttpRequest` object that
14 contains metadata about the request. Then Django loads the appropriate view,
15 passing the :class:`HttpRequest` as the first argument to the view function.
16 Each view is responsible for returning an :class:`HttpResponse` object.
17
18 This document explains the APIs for :class:`HttpRequest` and
19 :class:`HttpResponse` objects, which are defined in the :mod:`django.http`
20 module.
21
22 ``HttpRequest`` objects
23 =======================
24
25 .. class:: HttpRequest
26
27 .. _httprequest-attributes:
28
29 Attributes
30 ----------
31
32 All attributes should be considered read-only, unless stated otherwise.
33
34 .. attribute:: HttpRequest.scheme
35
36 A string representing the scheme of the request (``http`` or ``https``
37 usually).
38
39 .. attribute:: HttpRequest.body
40
41 The raw HTTP request body as a bytestring. This is useful for processing
42 data in different ways than conventional HTML forms: binary images,
43 XML payload etc. For processing conventional form data, use
44 :attr:`HttpRequest.POST`.
45
46 You can also read from an ``HttpRequest`` using a file-like interface with
47 :meth:`HttpRequest.read` or :meth:`HttpRequest.readline`. Accessing
48 the ``body`` attribute *after* reading the request with either of these I/O
49 stream methods will produce a ``RawPostDataException``.
50
51 .. attribute:: HttpRequest.path
52
53 A string representing the full path to the requested page, not including
54 the scheme, domain, or query string.
55
56 Example: ``"/music/bands/the_beatles/"``
57
58 .. attribute:: HttpRequest.path_info
59
60 Under some web server configurations, the portion of the URL after the
61 host name is split up into a script prefix portion and a path info
62 portion. The ``path_info`` attribute always contains the path info portion
63 of the path, no matter what web server is being used. Using this instead
64 of :attr:`~HttpRequest.path` can make your code easier to move between
65 test and deployment servers.
66
67 For example, if the ``WSGIScriptAlias`` for your application is set to
68 ``"/minfo"``, then ``path`` might be ``"/minfo/music/bands/the_beatles/"``
69 and ``path_info`` would be ``"/music/bands/the_beatles/"``.
70
71 .. attribute:: HttpRequest.method
72
73 A string representing the HTTP method used in the request. This is
74 guaranteed to be uppercase. For example::
75
76 if request.method == "GET":
77 do_something()
78 elif request.method == "POST":
79 do_something_else()
80
81 .. attribute:: HttpRequest.encoding
82
83 A string representing the current encoding used to decode form submission
84 data (or ``None``, which means the :setting:`DEFAULT_CHARSET` setting is
85 used). You can write to this attribute to change the encoding used when
86 accessing the form data. Any subsequent attribute accesses (such as reading
87 from :attr:`GET` or :attr:`POST`) will use the new ``encoding`` value.
88 Useful if you know the form data is not in the :setting:`DEFAULT_CHARSET`
89 encoding.
90
91 .. attribute:: HttpRequest.content_type
92
93 A string representing the MIME type of the request, parsed from the
94 ``CONTENT_TYPE`` header.
95
96 .. attribute:: HttpRequest.content_params
97
98 A dictionary of key/value parameters included in the ``CONTENT_TYPE``
99 header.
100
101 .. attribute:: HttpRequest.GET
102
103 A dictionary-like object containing all given HTTP GET parameters. See the
104 :class:`QueryDict` documentation below.
105
106 .. attribute:: HttpRequest.POST
107
108 A dictionary-like object containing all given HTTP POST parameters,
109 providing that the request contains form data. See the
110 :class:`QueryDict` documentation below. If you need to access raw or
111 non-form data posted in the request, access this through the
112 :attr:`HttpRequest.body` attribute instead.
113
114 It's possible that a request can come in via POST with an empty ``POST``
115 dictionary -- if, say, a form is requested via the POST HTTP method but
116 does not include form data. Therefore, you shouldn't use ``if request.POST``
117 to check for use of the POST method; instead, use ``if request.method ==
118 "POST"`` (see :attr:`HttpRequest.method`).
119
120 ``POST`` does *not* include file-upload information. See :attr:`FILES`.
121
122 .. attribute:: HttpRequest.COOKIES
123
124 A dictionary containing all cookies. Keys and values are strings.
125
126 .. attribute:: HttpRequest.FILES
127
128 A dictionary-like object containing all uploaded files. Each key in
129 ``FILES`` is the ``name`` from the ``<input type="file" name="">``. Each
130 value in ``FILES`` is an :class:`~django.core.files.uploadedfile.UploadedFile`.
131
132 See :doc:`/topics/files` for more information.
133
134 ``FILES`` will only contain data if the request method was POST and the
135 ``<form>`` that posted to the request had ``enctype="multipart/form-data"``.
136 Otherwise, ``FILES`` will be a blank dictionary-like object.
137
138 .. attribute:: HttpRequest.META
139
140 A dictionary containing all available HTTP headers. Available headers
141 depend on the client and server, but here are some examples:
142
143 * ``CONTENT_LENGTH`` -- The length of the request body (as a string).
144 * ``CONTENT_TYPE`` -- The MIME type of the request body.
145 * ``HTTP_ACCEPT`` -- Acceptable content types for the response.
146 * ``HTTP_ACCEPT_ENCODING`` -- Acceptable encodings for the response.
147 * ``HTTP_ACCEPT_LANGUAGE`` -- Acceptable languages for the response.
148 * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
149 * ``HTTP_REFERER`` -- The referring page, if any.
150 * ``HTTP_USER_AGENT`` -- The client's user-agent string.
151 * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
152 * ``REMOTE_ADDR`` -- The IP address of the client.
153 * ``REMOTE_HOST`` -- The hostname of the client.
154 * ``REMOTE_USER`` -- The user authenticated by the web server, if any.
155 * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
156 * ``SERVER_NAME`` -- The hostname of the server.
157 * ``SERVER_PORT`` -- The port of the server (as a string).
158
159 With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given
160 above, any HTTP headers in the request are converted to ``META`` keys by
161 converting all characters to uppercase, replacing any hyphens with
162 underscores and adding an ``HTTP_`` prefix to the name. So, for example, a
163 header called ``X-Bender`` would be mapped to the ``META`` key
164 ``HTTP_X_BENDER``.
165
166 Note that :djadmin:`runserver` strips all headers with underscores in the
167 name, so you won't see them in ``META``. This prevents header-spoofing
168 based on ambiguity between underscores and dashes both being normalizing to
169 underscores in WSGI environment variables. It matches the behavior of
170 web servers like Nginx and Apache 2.4+.
171
172 :attr:`HttpRequest.headers` is a simpler way to access all HTTP-prefixed
173 headers, plus ``CONTENT_LENGTH`` and ``CONTENT_TYPE``.
174
175 .. attribute:: HttpRequest.headers
176
177 A case insensitive, dict-like object that provides access to all
178 HTTP-prefixed headers (plus ``Content-Length`` and ``Content-Type``) from
179 the request.
180
181 The name of each header is stylized with title-casing (e.g. ``User-Agent``)
182 when it's displayed. You can access headers case-insensitively:
183
184 .. code-block:: pycon
185
186 >>> request.headers
187 {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}
188
189 >>> "User-Agent" in request.headers
190 True
191 >>> "user-agent" in request.headers
192 True
193
194 >>> request.headers["User-Agent"]
195 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
196 >>> request.headers["user-agent"]
197 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
198
199 >>> request.headers.get("User-Agent")
200 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
201 >>> request.headers.get("user-agent")
202 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
203
204 For use in, for example, Django templates, headers can also be looked up
205 using underscores in place of hyphens:
206
207 .. code-block:: html+django
208
209 {{ request.headers.user_agent }}
210
211 .. attribute:: HttpRequest.resolver_match
212
213 An instance of :class:`~django.urls.ResolverMatch` representing the
214 resolved URL. This attribute is only set after URL resolving took place,
215 which means it's available in all views but not in middleware which are
216 executed before URL resolving takes place (you can use it in
217 :meth:`process_view` though).
218
219 Attributes set by application code
220 ----------------------------------
221
222 Django doesn't set these attributes itself but makes use of them if set by your
223 application.
224
225 .. attribute:: HttpRequest.current_app
226
227 The :ttag:`url` template tag will use its value as the ``current_app``
228 argument to :func:`~django.urls.reverse()`.
229
230 .. attribute:: HttpRequest.urlconf
231
232 This will be used as the root URLconf for the current request, overriding
233 the :setting:`ROOT_URLCONF` setting. See
234 :ref:`how-django-processes-a-request` for details.
235
236 ``urlconf`` can be set to ``None`` to revert any changes made by previous
237 middleware and return to using the :setting:`ROOT_URLCONF`.
238
239 .. attribute:: HttpRequest.exception_reporter_filter
240
241 This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER`
242 for the current request. See :ref:`custom-error-reports` for details.
243
244 .. attribute:: HttpRequest.exception_reporter_class
245
246 This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER` for the
247 current request. See :ref:`custom-error-reports` for details.
248
249 Attributes set by middleware
250 ----------------------------
251
252 Some of the middleware included in Django's contrib apps set attributes on the
253 request. If you don't see the attribute on a request, be sure the appropriate
254 middleware class is listed in :setting:`MIDDLEWARE`.
255
256 .. attribute:: HttpRequest.session
257
258 From the :class:`~django.contrib.sessions.middleware.SessionMiddleware`: A
259 readable and writable, dictionary-like object that represents the current
260 session.
261
262 .. attribute:: HttpRequest.site
263
264 From the :class:`~django.contrib.sites.middleware.CurrentSiteMiddleware`:
265 An instance of :class:`~django.contrib.sites.models.Site` or
266 :class:`~django.contrib.sites.requests.RequestSite` as returned by
267 :func:`~django.contrib.sites.shortcuts.get_current_site()`
268 representing the current site.
269
270 .. attribute:: HttpRequest.user
271
272 From the :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`:
273 An instance of :setting:`AUTH_USER_MODEL` representing the currently
274 logged-in user. If the user isn't currently logged in, ``user`` will be set
275 to an instance of :class:`~django.contrib.auth.models.AnonymousUser`. You
276 can tell them apart with
277 :attr:`~django.contrib.auth.models.User.is_authenticated`, like so::
278
279 if request.user.is_authenticated:
280 ... # Do something for logged-in users.
281 else:
282 ... # Do something for anonymous users.
283
284 The :meth:`auser` method does the same thing but can be used from async
285 contexts.
286
287 Methods
288 -------
289
290 .. method:: HttpRequest.auser()
291
292 From the :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`:
293 Coroutine. Returns an instance of :setting:`AUTH_USER_MODEL` representing
294 the currently logged-in user. If the user isn't currently logged in,
295 ``auser`` will return an instance of
296 :class:`~django.contrib.auth.models.AnonymousUser`. This is similar to the
297 :attr:`user` attribute but it works in async contexts.
298
299 .. method:: HttpRequest.get_host()
300
301 Returns the originating host of the request using information from the
302 ``HTTP_X_FORWARDED_HOST`` (if :setting:`USE_X_FORWARDED_HOST` is enabled)
303 and ``HTTP_HOST`` headers, in that order. If they don't provide a value,
304 the method uses a combination of ``SERVER_NAME`` and ``SERVER_PORT`` as
305 detailed in :pep:`3333`.
306
307 Example: ``"127.0.0.1:8000"``
308
309 Raises ``django.core.exceptions.DisallowedHost`` if the host is not in
310 :setting:`ALLOWED_HOSTS` or the domain name is invalid according to
311 :rfc:`1034`/:rfc:`1035 <1035>`.
312
313 .. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is
314 behind multiple proxies. One solution is to use middleware to rewrite
315 the proxy headers, as in the following example::
316
317 class MultipleProxyMiddleware:
318 FORWARDED_FOR_FIELDS = [
319 "HTTP_X_FORWARDED_FOR",
320 "HTTP_X_FORWARDED_HOST",
321 "HTTP_X_FORWARDED_SERVER",
322 ]
323
324 def __init__(self, get_response):
325 self.get_response = get_response
326
327 def __call__(self, request):
328 """
329 Rewrites the proxy headers so that only the most
330 recent proxy is used.
331 """
332 for field in self.FORWARDED_FOR_FIELDS:
333 if field in request.META:
334 if "," in request.META[field]:
335 parts = request.META[field].split(",")
336 request.META[field] = parts[-1].strip()
337 return self.get_response(request)
338
339 This middleware should be positioned before any other middleware that
340 relies on the value of :meth:`~HttpRequest.get_host()` -- for instance,
341 :class:`~django.middleware.common.CommonMiddleware` or
342 :class:`~django.middleware.csrf.CsrfViewMiddleware`.
343
344 .. method:: HttpRequest.get_port()
345
346 Returns the originating port of the request using information from the
347 ``HTTP_X_FORWARDED_PORT`` (if :setting:`USE_X_FORWARDED_PORT` is enabled)
348 and ``SERVER_PORT`` ``META`` variables, in that order.
349
350 .. method:: HttpRequest.get_full_path()
351
352 Returns the ``path``, plus an appended query string, if applicable.
353
354 Example: ``"/music/bands/the_beatles/?print=true"``
355
356 .. method:: HttpRequest.get_full_path_info()
357
358 Like :meth:`get_full_path`, but uses :attr:`path_info` instead of
359 :attr:`path`.
360
361 Example: ``"/minfo/music/bands/the_beatles/?print=true"``
362
363 .. method:: HttpRequest.build_absolute_uri(location=None)
364
365 Returns the absolute URI form of ``location``. If no location is provided,
366 the location will be set to ``request.get_full_path()``.
367
368 If the location is already an absolute URI, it will not be altered.
369 Otherwise the absolute URI is built using the server variables available in
370 this request. For example:
371
372 .. code-block:: pycon
373
374 >>> request.build_absolute_uri()
375 'https://example.com/music/bands/the_beatles/?print=true'
376 >>> request.build_absolute_uri("/bands/")
377 'https://example.com/bands/'
378 >>> request.build_absolute_uri("https://example2.com/bands/")
379 'https://example2.com/bands/'
380
381 .. note::
382
383 Mixing HTTP and HTTPS on the same site is discouraged, therefore
384 :meth:`~HttpRequest.build_absolute_uri()` will always generate an
385 absolute URI with the same scheme the current request has. If you need
386 to redirect users to HTTPS, it's best to let your web server redirect
387 all HTTP traffic to HTTPS.
388
389 .. method:: HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
390
391 Returns a cookie value for a signed cookie, or raises a
392 ``django.core.signing.BadSignature`` exception if the signature is
393 no longer valid. If you provide the ``default`` argument the exception
394 will be suppressed and that default value will be returned instead.
395
396 The optional ``salt`` argument can be used to put the cookie into a
397 separate signature namespace. If supplied, the ``max_age`` argument will
398 be checked against the signed timestamp attached to the cookie value to
399 ensure the cookie is not older than ``max_age`` seconds.
400
401 Cookies signed by older Django versions are accepted by default for
402 backwards compatibility. Set :setting:`SIGNED_COOKIE_LEGACY_SALT_FALLBACK`
403 to ``False`` to reject them.
404
405 For example:
406
407 .. code-block:: pycon
408
409 >>> request.get_signed_cookie("name")
410 'Tony'
411 >>> request.get_signed_cookie("name", salt="name-salt")
412 'Tony' # assuming cookie was set using the same salt
413 >>> request.get_signed_cookie("nonexistent-cookie")
414 KeyError: 'nonexistent-cookie'
415 >>> request.get_signed_cookie("nonexistent-cookie", False)
416 False
417 >>> request.get_signed_cookie("cookie-that-was-tampered-with")
418 BadSignature: ...
419 >>> request.get_signed_cookie("name", max_age=60)
420 SignatureExpired: Signature age 1677.3839159 > 60 seconds
421 >>> request.get_signed_cookie("name", False, max_age=60)
422 False
423
424 See :doc:`cryptographic signing </topics/signing>` for more information.
425
426 .. versionchanged:: 5.2.15
427
428 In older versions, cookies signed with distinct ``(key, salt)`` pairs
429 that concatenate to the same string could be used interchangeably.
430
431 .. method:: HttpRequest.is_secure()
432
433 Returns ``True`` if the request is secure; that is, if it was made with
434 HTTPS.
435
436 .. method:: HttpRequest.get_preferred_type(media_types)
437
438 .. versionadded:: 5.2
439
440 Returns the preferred mime type from ``media_types``, based on the
441 ``Accept`` header, or ``None`` if the client does not accept any of the
442 provided types.
443
444 Assuming the client sends an ``Accept`` header of
445 ``text/html,application/json;q=0.8``:
446
447 .. code-block:: pycon
448
449 >>> request.get_preferred_type(["text/html", "application/json"])
450 "text/html"
451 >>> request.get_preferred_type(["application/json", "text/plain"])
452 "application/json"
453 >>> request.get_preferred_type(["application/xml", "text/plain"])
454 None
455
456 If the mime type includes parameters, these are also considered when
457 determining the preferred media type. For example, with an ``Accept``
458 header of ``text/vcard;version=3.0,text/html;q=0.5``, the return value of
459 ``request.get_preferred_type()`` depends on the available media types:
460
461 .. code-block:: pycon
462
463 >>> request.get_preferred_type(
464 ... [
465 ... "text/vcard; version=4.0",
466 ... "text/vcard; version=3.0",
467 ... "text/vcard",
468 ... "text/directory",
469 ... ]
470 ... )
471 "text/vcard; version=3.0"
472 >>> request.get_preferred_type(
473 ... [
474 ... "text/vcard; version=4.0",
475 ... "text/html",
476 ... ]
477 ... )
478 "text/html"
479 >>> request.get_preferred_type(
480 ... [
481 ... "text/vcard; version=4.0",
482 ... "text/vcard",
483 ... "text/directory",
484 ... ]
485 ... )
486 None
487
488 (For further details on how content negotiation is performed, see
489 :rfc:`9110#section-12.5.1`.)
490
491 Most browsers send ``Accept: */*`` by default, meaning they don't have a
492 preference, in which case the first item in ``media_types`` would be
493 returned.
494
495 Setting an explicit ``Accept`` header in API requests can be useful for
496 returning a different content type for those consumers only. See
497 :ref:`content-negotiation-example` for an example of returning
498 different content based on the ``Accept`` header.
499
500 .. note::
501
502 If a response varies depending on the content of the ``Accept`` header
503 and you are using some form of caching like Django's
504 :mod:`cache middleware <django.middleware.cache>`, you should decorate
505 the view with :func:`vary_on_headers('Accept')
506 <django.views.decorators.vary.vary_on_headers>` so that the responses
507 are properly cached.
508
509 .. method:: HttpRequest.accepts(mime_type)
510
511 Returns ``True`` if the request's ``Accept`` header matches the
512 ``mime_type`` argument:
513
514 .. code-block:: pycon
515
516 >>> request.accepts("text/html")
517 True
518
519 Most browsers send ``Accept: */*`` by default, so this would return
520 ``True`` for all content types.
521
522 See :ref:`content-negotiation-example` for an example of using
523 ``accepts()`` to return different content based on the ``Accept`` header.
524
525 .. method:: HttpRequest.read(size=None)
526 .. method:: HttpRequest.readline()
527 .. method:: HttpRequest.readlines()
528 .. method:: HttpRequest.__iter__()
529
530 Methods implementing a file-like interface for reading from an
531 ``HttpRequest`` instance. This makes it possible to consume an incoming
532 request in a streaming fashion. A common use-case would be to process a
533 big XML payload with an iterative parser without constructing a whole
534 XML tree in memory.
535
536 Given this standard interface, an ``HttpRequest`` instance can be
537 passed directly to an XML parser such as
538 :class:`~xml.etree.ElementTree.ElementTree`::
539
540 import xml.etree.ElementTree as ET
541
542 for element in ET.iterparse(request):
543 process(element)
544
545
546 ``QueryDict`` objects
547 =====================
548
549 .. class:: QueryDict
550
551 In an :class:`HttpRequest` object, the :attr:`~HttpRequest.GET` and
552 :attr:`~HttpRequest.POST` attributes are instances of ``django.http.QueryDict``,
553 a dictionary-like class customized to deal with multiple values for the same
554 key. This is necessary because some HTML form elements, notably
555 ``<select multiple>``, pass multiple values for the same key.
556
557 The ``QueryDict``\ s at ``request.POST`` and ``request.GET`` will be immutable
558 when accessed in a normal request/response cycle. To get a mutable version you
559 need to use :meth:`QueryDict.copy`.
560
561 Methods
562 -------
563
564 :class:`QueryDict` implements all the standard dictionary methods because it's
565 a subclass of dictionary. Exceptions are outlined here:
566
567 .. method:: QueryDict.__init__(query_string=None, mutable=False, encoding=None)
568
569 Instantiates a ``QueryDict`` object based on ``query_string``.
570
571 .. code-block:: pycon
572
573 >>> QueryDict("a=1&a=2&c=3")
574 <QueryDict: {'a': ['1', '2'], 'c': ['3']}>
575
576 If ``query_string`` is not passed in, the resulting ``QueryDict`` will be
577 empty (it will have no keys or values).
578
579 Most ``QueryDict``\ s you encounter, and in particular those at
580 ``request.POST`` and ``request.GET``, will be immutable. If you are
581 instantiating one yourself, you can make it mutable by passing
582 ``mutable=True`` to its ``__init__()``.
583
584 Strings for setting both keys and values will be converted from ``encoding``
585 to ``str``. If ``encoding`` is not set, it defaults to
586 :setting:`DEFAULT_CHARSET`.
587
588 .. classmethod:: QueryDict.fromkeys(iterable, value='', mutable=False, encoding=None)
589
590 Creates a new ``QueryDict`` with keys from ``iterable`` and each value
591 equal to ``value``. For example:
592
593 .. code-block:: pycon
594
595 >>> QueryDict.fromkeys(["a", "a", "b"], value="val")
596 <QueryDict: {'a': ['val', 'val'], 'b': ['val']}>
597
598 .. method:: QueryDict.__getitem__(key)
599
600 Returns the last value for the given key; or an empty list (``[]``) if the
601 key exists but has no values. Raises
602 ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
603 exist. (This is a subclass of Python's standard :exc:`KeyError`, so you can
604 stick to catching ``KeyError``.)
605
606 .. code-block:: pycon
607
608 >>> q = QueryDict("a=1&a=2&a=3", mutable=True)
609 >>> q.__getitem__("a")
610 '3'
611 >>> q.__setitem__("b", [])
612 >>> q.__getitem__("b")
613 []
614
615 .. method:: QueryDict.__setitem__(key, value)
616
617 Sets the given key to ``[value]`` (a list whose single element is
618 ``value``). Note that this, as other dictionary functions that have side
619 effects, can only be called on a mutable ``QueryDict`` (such as one that
620 was created via :meth:`QueryDict.copy`).
621
622 .. method:: QueryDict.__contains__(key)
623
624 Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
625 in request.GET``.
626
627 .. method:: QueryDict.get(key, default=None)
628
629 Uses the same logic as :meth:`__getitem__`, with a hook for returning a
630 default value if the key doesn't exist.
631
632 .. method:: QueryDict.setdefault(key, default=None)
633
634 Like :meth:`dict.setdefault`, except it uses :meth:`__setitem__` internally.
635
636 .. method:: QueryDict.update(other_dict)
637
638 Takes either a ``QueryDict`` or a dictionary. Like :meth:`dict.update`,
639 except it *appends* to the current dictionary items rather than replacing
640 them. For example:
641
642 .. code-block:: pycon
643
644 >>> q = QueryDict("a=1", mutable=True)
645 >>> q.update({"a": "2"})
646 >>> q.getlist("a")
647 ['1', '2']
648 >>> q["a"] # returns the last
649 '2'
650
651 .. method:: QueryDict.items()
652
653 Like :meth:`dict.items`, except this uses the same last-value logic as
654 :meth:`__getitem__` and returns an iterator object instead of a view object.
655 For example:
656
657 .. code-block:: pycon
658
659 >>> q = QueryDict("a=1&a=2&a=3")
660 >>> list(q.items())
661 [('a', '3')]
662
663 .. method:: QueryDict.values()
664
665 Like :meth:`dict.values`, except this uses the same last-value logic as
666 :meth:`__getitem__` and returns an iterator instead of a view object. For
667 example:
668
669 .. code-block:: pycon
670
671 >>> q = QueryDict("a=1&a=2&a=3")
672 >>> list(q.values())
673 ['3']
674
675 In addition, ``QueryDict`` has the following methods:
676
677 .. method:: QueryDict.copy()
678
679 Returns a copy of the object using :func:`copy.deepcopy`. This copy will
680 be mutable even if the original was not.
681
682 .. method:: QueryDict.getlist(key, default=None)
683
684 Returns a list of the data with the requested key. Returns an empty list if
685 the key doesn't exist and ``default`` is ``None``. It's guaranteed to
686 return a list unless the default value provided isn't a list.
687
688 .. method:: QueryDict.setlist(key, list_)
689
690 Sets the given key to ``list_`` (unlike :meth:`__setitem__`).
691
692 .. method:: QueryDict.appendlist(key, item)
693
694 Appends an item to the internal list associated with key.
695
696 .. method:: QueryDict.setlistdefault(key, default_list=None)
697
698 Like :meth:`setdefault`, except it takes a list of values instead of a
699 single value.
700
701 .. method:: QueryDict.lists()
702
703 Like :meth:`items()`, except it includes all values, as a list, for each
704 member of the dictionary. For example:
705
706 .. code-block:: pycon
707
708 >>> q = QueryDict("a=1&a=2&a=3")
709 >>> q.lists()
710 [('a', ['1', '2', '3'])]
711
712 .. method:: QueryDict.pop(key)
713
714 Returns a list of values for the given key and removes them from the
715 dictionary. Raises ``KeyError`` if the key does not exist. For example:
716
717 .. code-block:: pycon
718
719 >>> q = QueryDict("a=1&a=2&a=3", mutable=True)
720 >>> q.pop("a")
721 ['1', '2', '3']
722
723 .. method:: QueryDict.popitem()
724
725 Removes an arbitrary member of the dictionary (since there's no concept
726 of ordering), and returns a two value tuple containing the key and a list
727 of all values for the key. Raises ``KeyError`` when called on an empty
728 dictionary. For example:
729
730 .. code-block:: pycon
731
732 >>> q = QueryDict("a=1&a=2&a=3", mutable=True)
733 >>> q.popitem()
734 ('a', ['1', '2', '3'])
735
736 .. method:: QueryDict.dict()
737
738 Returns a ``dict`` representation of ``QueryDict``. For every (key, list)
739 pair in ``QueryDict``, ``dict`` will have (key, item), where item is one
740 element of the list, using the same logic as :meth:`QueryDict.__getitem__`:
741
742 .. code-block:: pycon
743
744 >>> q = QueryDict("a=1&a=3&a=5")
745 >>> q.dict()
746 {'a': '5'}
747
748 .. method:: QueryDict.urlencode(safe=None)
749
750 Returns a string of the data in query string format. For example:
751
752 .. code-block:: pycon
753
754 >>> q = QueryDict("a=2&b=3&b=5")
755 >>> q.urlencode()
756 'a=2&b=3&b=5'
757
758 Use the ``safe`` parameter to pass characters which don't require encoding.
759 For example:
760
761 .. code-block:: pycon
762
763 >>> q = QueryDict(mutable=True)
764 >>> q["next"] = "/a&b/"
765 >>> q.urlencode(safe="/")
766 'next=/a%26b/'
767
768 ``HttpResponse`` objects
769 ========================
770
771 .. class:: HttpResponse
772
773 In contrast to :class:`HttpRequest` objects, which are created automatically by
774 Django, :class:`HttpResponse` objects are your responsibility. Each view you
775 write is responsible for instantiating, populating, and returning an
776 :class:`HttpResponse`.
777
778 The :class:`HttpResponse` class lives in the :mod:`django.http` module.
779
780 Usage
781 -----
782
783 Passing strings
784 ~~~~~~~~~~~~~~~
785
786 Typical usage is to pass the contents of the page, as a string, bytestring,
787 or :class:`memoryview`, to the :class:`HttpResponse` constructor:
788
789 .. code-block:: pycon
790
791 >>> from django.http import HttpResponse
792 >>> response = HttpResponse("Here's the text of the web page.")
793 >>> response = HttpResponse("Text only, please.", content_type="text/plain")
794 >>> response = HttpResponse(b"Bytestrings are also accepted.")
795 >>> response = HttpResponse(memoryview(b"Memoryview as well."))
796
797 But if you want to add content incrementally, you can use ``response`` as a
798 file-like object:
799
800 .. code-block:: pycon
801
802 >>> response = HttpResponse()
803 >>> response.write("<p>Here's the text of the web page.</p>")
804 >>> response.write("<p>Here's another paragraph.</p>")
805
806 Passing iterators
807 ~~~~~~~~~~~~~~~~~
808
809 Finally, you can pass ``HttpResponse`` an iterator rather than strings.
810 ``HttpResponse`` will consume the iterator immediately, store its content as a
811 string, and discard it. Objects with a ``close()`` method such as files and
812 generators are immediately closed.
813
814 If you need the response to be streamed from the iterator to the client, you
815 must use the :class:`StreamingHttpResponse` class instead.
816
817 .. _setting-header-fields:
818
819 Setting header fields
820 ~~~~~~~~~~~~~~~~~~~~~
821
822 To set or remove a header field in your response, use
823 :attr:`HttpResponse.headers`:
824
825 .. code-block:: pycon
826
827 >>> response = HttpResponse()
828 >>> response.headers["Age"] = 120
829 >>> del response.headers["Age"]
830
831 You can also manipulate headers by treating your response like a dictionary:
832
833 .. code-block:: pycon
834
835 >>> response = HttpResponse()
836 >>> response["Age"] = 120
837 >>> del response["Age"]
838
839 This proxies to ``HttpResponse.headers``, and is the original interface offered
840 by ``HttpResponse``.
841
842 When using this interface, unlike a dictionary, ``del`` doesn't raise
843 ``KeyError`` if the header field doesn't exist.
844
845 You can also set headers on instantiation:
846
847 .. code-block:: pycon
848
849 >>> response = HttpResponse(headers={"Age": 120})
850
851 For setting the ``Cache-Control`` and ``Vary`` header fields, it is recommended
852 to use the :func:`~django.utils.cache.patch_cache_control` and
853 :func:`~django.utils.cache.patch_vary_headers` methods from
854 :mod:`django.utils.cache`, since these fields can have multiple, comma-separated
855 values. The "patch" methods ensure that other values, e.g. added by a
856 middleware, are not removed.
857
858 HTTP header fields cannot contain newlines. An attempt to set a header field
859 containing a newline character (CR or LF) will raise ``BadHeaderError``
860
861 Telling the browser to treat the response as a file attachment
862 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
863
864 To tell the browser to treat the response as a file attachment, set the
865 ``Content-Type`` and ``Content-Disposition`` headers. For example, this is how
866 you might return a Microsoft Excel spreadsheet:
867
868 .. code-block:: pycon
869
870 >>> response = HttpResponse(
871 ... my_data,
872 ... headers={
873 ... "Content-Type": "application/vnd.ms-excel",
874 ... "Content-Disposition": 'attachment; filename="foo.xls"',
875 ... },
876 ... )
877
878 There's nothing Django-specific about the ``Content-Disposition`` header, but
879 it's easy to forget the syntax, so we've included it here.
880
881 Attributes
882 ----------
883
884 .. attribute:: HttpResponse.content
885
886 A bytestring representing the content, encoded from a string if necessary.
887
888 .. attribute:: HttpResponse.text
889
890 .. versionadded:: 5.2
891
892 A string representation of :attr:`HttpResponse.content`, decoded using the
893 response's :attr:`HttpResponse.charset` (defaulting to ``UTF-8`` if empty).
894
895 .. attribute:: HttpResponse.cookies
896
897 A :py:obj:`http.cookies.SimpleCookie` object holding the cookies included
898 in the response.
899
900 .. attribute:: HttpResponse.headers
901
902 A case insensitive, dict-like object that provides an interface to all
903 HTTP headers on the response, except a ``Set-Cookie`` header. See
904 :ref:`setting-header-fields` and :attr:`HttpResponse.cookies`.
905
906 .. attribute:: HttpResponse.charset
907
908 A string denoting the charset in which the response will be encoded. If not
909 given at ``HttpResponse`` instantiation time, it will be extracted from
910 ``content_type`` and if that is unsuccessful, the
911 :setting:`DEFAULT_CHARSET` setting will be used.
912
913 .. attribute:: HttpResponse.status_code
914
915 The :rfc:`HTTP status code <9110#section-15>` for the response.
916
917 Unless :attr:`reason_phrase` is explicitly set, modifying the value of
918 ``status_code`` outside the constructor will also modify the value of
919 ``reason_phrase``.
920
921 .. attribute:: HttpResponse.reason_phrase
922
923 The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
924 <9110#section-15.1>` default reason phrases.
925
926 Unless explicitly set, ``reason_phrase`` is determined by the value of
927 :attr:`status_code`.
928
929 .. attribute:: HttpResponse.streaming
930
931 This is always ``False``.
932
933 This attribute exists so middleware can treat streaming responses
934 differently from regular responses.
935
936 .. attribute:: HttpResponse.closed
937
938 ``True`` if the response has been closed.
939
940 Methods
941 -------
942
943 .. method:: HttpResponse.__init__(content=b'', content_type=None, status=200, reason=None, charset=None, headers=None)
944
945 Instantiates an ``HttpResponse`` object with the given page content,
946 content type, and headers.
947
948 ``content`` is most commonly an iterator, bytestring, :class:`memoryview`,
949 or string. Other types will be converted to a bytestring by encoding their
950 string representation. Iterators should return strings or bytestrings and
951 those will be joined together to form the content of the response.
952
953 ``content_type`` is the MIME type optionally completed by a character set
954 encoding and is used to fill the HTTP ``Content-Type`` header. If not
955 specified, it is formed by ``'text/html'`` and the
956 :setting:`DEFAULT_CHARSET` settings, by default:
957 ``"text/html; charset=utf-8"``.
958
959 ``status`` is the :rfc:`HTTP status code <9110#section-15>` for the
960 response. You can use Python's :py:class:`http.HTTPStatus` for meaningful
961 aliases, such as ``HTTPStatus.NO_CONTENT``.
962
963 ``reason`` is the HTTP response phrase. If not provided, a default phrase
964 will be used.
965
966 ``charset`` is the charset in which the response will be encoded. If not
967 given it will be extracted from ``content_type``, and if that
968 is unsuccessful, the :setting:`DEFAULT_CHARSET` setting will be used.
969
970 ``headers`` is a :class:`dict` of HTTP headers for the response.
971
972 .. method:: HttpResponse.__setitem__(header, value)
973
974 Sets the given header name to the given value. Both ``header`` and
975 ``value`` should be strings.
976
977 .. method:: HttpResponse.__delitem__(header)
978
979 Deletes the header with the given name. Fails silently if the header
980 doesn't exist. Case-insensitive.
981
982 .. method:: HttpResponse.__getitem__(header)
983
984 Returns the value for the given header name. Case-insensitive.
985
986 .. method:: HttpResponse.get(header, alternate=None)
987
988 Returns the value for the given header, or an ``alternate`` if the header
989 doesn't exist.
990
991 .. method:: HttpResponse.has_header(header)
992
993 Returns ``True`` or ``False`` based on a case-insensitive check for a
994 header with the given name.
995
996 .. method:: HttpResponse.items()
997
998 Acts like :meth:`dict.items` for HTTP headers on the response.
999
1000 .. method:: HttpResponse.setdefault(header, value)
1001
1002 Sets a header unless it has already been set.
1003
1004 .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
1005
1006 Sets a cookie. The parameters are the same as in the
1007 :class:`~http.cookies.Morsel` cookie object in the Python standard library.
1008
1009 * ``max_age`` should be a :class:`~datetime.timedelta` object, an integer
1010 number of seconds, or ``None`` (default) if the cookie should last only
1011 as long as the client's browser session. If ``expires`` is not specified,
1012 it will be calculated.
1013 * ``expires`` should either be a string in the format
1014 ``"Wdy, DD-Mon-YY HH:MM:SS GMT"`` or a ``datetime.datetime`` object
1015 in UTC. If ``expires`` is a ``datetime`` object, the ``max_age``
1016 will be calculated.
1017 * Use ``domain`` if you want to set a cross-domain cookie. For example,
1018 ``domain="example.com"`` will set a cookie that is readable by the
1019 domains www.example.com, blog.example.com, etc. Otherwise, a cookie will
1020 only be readable by the domain that set it.
1021 * Use ``secure=True`` if you want the cookie to be only sent to the server
1022 when a request is made with the ``https`` scheme.
1023 * Use ``httponly=True`` if you want to prevent client-side
1024 JavaScript from having access to the cookie.
1025
1026 HttpOnly_ is a flag included in a Set-Cookie HTTP response header. It's
1027 part of the :rfc:`RFC 6265 <6265#section-4.1.2.6>` standard for cookies
1028 and can be a useful way to mitigate the risk of a client-side script
1029 accessing the protected cookie data.
1030 * Use ``samesite='Strict'`` or ``samesite='Lax'`` to tell the browser not
1031 to send this cookie when performing a cross-origin request. `SameSite`_
1032 isn't supported by all browsers, so it's not a replacement for Django's
1033 CSRF protection, but rather a defense in depth measure.
1034
1035 Use ``samesite='None'`` (string) to explicitly state that this cookie is
1036 sent with all same-site and cross-site requests.
1037
1038 .. _HttpOnly: https://owasp.org/www-community/HttpOnly
1039 .. _SameSite: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
1040
1041 .. warning::
1042
1043 :rfc:`RFC 6265 <6265#section-6.1>` states that user agents should
1044 support cookies of at least 4096 bytes. For many browsers this is also
1045 the maximum size. Django will not raise an exception if there's an
1046 attempt to store a cookie of more than 4096 bytes, but many browsers
1047 will not set the cookie correctly.
1048
1049 .. method:: HttpResponse.set_signed_cookie(key, value, salt='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
1050
1051 Like :meth:`~HttpResponse.set_cookie()`, but
1052 :doc:`cryptographic signing </topics/signing>` the cookie before setting
1053 it. Use in conjunction with :meth:`HttpRequest.get_signed_cookie`.
1054 You can use the optional ``salt`` argument to put the cookie into a
1055 separate signature namespace, but you will need to remember to pass it to
1056 the corresponding
1057 :meth:`HttpRequest.get_signed_cookie` call.
1058
1059 .. method:: HttpResponse.delete_cookie(key, path='/', domain=None, samesite=None)
1060
1061 Deletes the cookie with the given key. Fails silently if the key doesn't
1062 exist.
1063
1064 Due to the way cookies work, ``path`` and ``domain`` should be the same
1065 values you used in ``set_cookie()`` -- otherwise the cookie may not be
1066 deleted.
1067
1068 .. method:: HttpResponse.close()
1069
1070 This method is called at the end of the request directly by the WSGI
1071 server.
1072
1073 .. method:: HttpResponse.write(content)
1074
1075 This method makes an :class:`HttpResponse` instance a file-like object.
1076
1077 .. method:: HttpResponse.flush()
1078
1079 This method makes an :class:`HttpResponse` instance a file-like object.
1080
1081 .. method:: HttpResponse.tell()
1082
1083 This method makes an :class:`HttpResponse` instance a file-like object.
1084
1085 .. method:: HttpResponse.getvalue()
1086
1087 Returns the value of :attr:`HttpResponse.content`. This method makes
1088 an :class:`HttpResponse` instance a stream-like object.
1089
1090 .. method:: HttpResponse.readable()
1091
1092 Always ``False``. This method makes an :class:`HttpResponse` instance a
1093 stream-like object.
1094
1095 .. method:: HttpResponse.seekable()
1096
1097 Always ``False``. This method makes an :class:`HttpResponse` instance a
1098 stream-like object.
1099
1100 .. method:: HttpResponse.writable()
1101
1102 Always ``True``. This method makes an :class:`HttpResponse` instance a
1103 stream-like object.
1104
1105 .. method:: HttpResponse.writelines(lines)
1106
1107 Writes a list of lines to the response. Line separators are not added. This
1108 method makes an :class:`HttpResponse` instance a stream-like object.
1109
1110 .. _ref-httpresponse-subclasses:
1111
1112 ``HttpResponse`` subclasses
1113 ---------------------------
1114
1115 Django includes a number of ``HttpResponse`` subclasses that handle different
1116 types of HTTP responses. Like ``HttpResponse``, these subclasses live in
1117 :mod:`django.http`.
1118
1119 .. class:: HttpResponseRedirect
1120
1121 The first argument to the constructor is required -- the path to redirect
1122 to. This can be a fully qualified URL
1123 (e.g. ``'https://www.yahoo.com/search/'``), an absolute path with no domain
1124 (e.g. ``'/search/'``), or even a relative path (e.g. ``'search/'``). In that
1125 last case, the client browser will reconstruct the full URL itself
1126 according to the current path.
1127
1128 The constructor accepts an optional ``preserve_request`` keyword argument
1129 that defaults to ``False``, producing a response with a 302 status code. If
1130 ``preserve_request`` is ``True``, the status code will be 307 instead.
1131
1132 See :class:`HttpResponse` for other optional constructor arguments.
1133
1134 .. attribute:: HttpResponseRedirect.url
1135
1136 This read-only attribute represents the URL the response will redirect
1137 to (equivalent to the ``Location`` response header).
1138
1139 .. versionchanged:: 5.2
1140
1141 The ``preserve_request`` argument was added.
1142
1143 .. class:: HttpResponsePermanentRedirect
1144
1145 Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
1146 (HTTP status code 301) instead of a "found" redirect (status code 302).
1147 When ``preserve_request=True``, the response's status code is 308.
1148
1149 .. versionchanged:: 5.2
1150
1151 The ``preserve_request`` argument was added.
1152
1153 .. class:: HttpResponseNotModified
1154
1155 The constructor doesn't take any arguments and no content should be added
1156 to this response. Use this to designate that a page hasn't been modified
1157 since the user's last request (status code 304).
1158
1159 .. class:: HttpResponseBadRequest
1160
1161 Acts just like :class:`HttpResponse` but uses a 400 status code.
1162
1163 .. class:: HttpResponseNotFound
1164
1165 Acts just like :class:`HttpResponse` but uses a 404 status code.
1166
1167 .. class:: HttpResponseForbidden
1168
1169 Acts just like :class:`HttpResponse` but uses a 403 status code.
1170
1171 .. class:: HttpResponseNotAllowed
1172
1173 Like :class:`HttpResponse`, but uses a 405 status code. The first argument
1174 to the constructor is required: a list of permitted methods (e.g.
1175 ``['GET', 'POST']``).
1176
1177 .. class:: HttpResponseGone
1178
1179 Acts just like :class:`HttpResponse` but uses a 410 status code.
1180
1181 .. class:: HttpResponseServerError
1182
1183 Acts just like :class:`HttpResponse` but uses a 500 status code.
1184
1185 .. note::
1186
1187 If a custom subclass of :class:`HttpResponse` implements a ``render``
1188 method, Django will treat it as emulating a
1189 :class:`~django.template.response.SimpleTemplateResponse`, and the
1190 ``render`` method must itself return a valid response object.
1191
1192 Custom response classes
1193 ~~~~~~~~~~~~~~~~~~~~~~~
1194
1195 If you find yourself needing a response class that Django doesn't provide, you
1196 can create it with the help of :py:class:`http.HTTPStatus`. For example::
1197
1198 from http import HTTPStatus
1199 from django.http import HttpResponse
1200
1201
1202 class HttpResponseNoContent(HttpResponse):
1203 status_code = HTTPStatus.NO_CONTENT
1204
1205 ``JsonResponse`` objects
1206 ========================
1207
1208 .. class:: JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
1209
1210 An :class:`HttpResponse` subclass that helps to create a JSON-encoded
1211 response. It inherits most behavior from its superclass with a couple
1212 differences:
1213
1214 Its default ``Content-Type`` header is set to :mimetype:`application/json`.
1215
1216 The first parameter, ``data``, should be a ``dict`` instance. If the
1217 ``safe`` parameter is set to ``False`` (see below) it can be any
1218 JSON-serializable object.
1219
1220 The ``encoder``, which defaults to
1221 :class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to
1222 serialize the data. See :ref:`JSON serialization
1223 <serialization-formats-json>` for more details about this serializer.
1224
1225 The ``safe`` boolean parameter defaults to ``True``. If it's set to
1226 ``False``, any object can be passed for serialization (otherwise only
1227 ``dict`` instances are allowed). If ``safe`` is ``True`` and a non-``dict``
1228 object is passed as the first argument, a :exc:`TypeError` will be raised.
1229
1230 The ``json_dumps_params`` parameter is a dictionary of keyword arguments
1231 to pass to the ``json.dumps()`` call used to generate the response.
1232
1233 Usage
1234 -----
1235
1236 Typical usage could look like:
1237
1238 .. code-block:: pycon
1239
1240 >>> from django.http import JsonResponse
1241 >>> response = JsonResponse({"foo": "bar"})
1242 >>> response.content
1243 b'{"foo": "bar"}'
1244
1245 Serializing non-dictionary objects
1246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1247
1248 In order to serialize objects other than ``dict`` you must set the ``safe``
1249 parameter to ``False``:
1250
1251 .. code-block:: pycon
1252
1253 >>> response = JsonResponse([1, 2, 3], safe=False)
1254
1255 Without passing ``safe=False``, a :exc:`TypeError` will be raised.
1256
1257 Note that an API based on ``dict`` objects is more extensible, flexible, and
1258 makes it easier to maintain forwards compatibility. Therefore, you should avoid
1259 using non-dict objects in JSON-encoded response.
1260
1261 .. warning::
1262
1263 Before the `5th edition of ECMAScript
1264 <https://262.ecma-international.org/5.1/#sec-11.1.4>`_ it was possible to
1265 poison the JavaScript ``Array`` constructor. For this reason, Django does
1266 not allow passing non-dict objects to the
1267 :class:`~django.http.JsonResponse` constructor by default. However, most
1268 modern browsers implement ECMAScript 5 which removes this attack vector.
1269 Therefore it is possible to disable this security precaution.
1270
1271 Changing the default JSON encoder
1272 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1273
1274 If you need to use a different JSON encoder class you can pass the ``encoder``
1275 parameter to the constructor method:
1276
1277 .. code-block:: pycon
1278
1279 >>> response = JsonResponse(data, encoder=MyJSONEncoder)
1280
1281 .. _httpresponse-streaming:
1282
1283 ``StreamingHttpResponse`` objects
1284 =================================
1285
1286 .. class:: StreamingHttpResponse
1287
1288 The :class:`StreamingHttpResponse` class is used to stream a response from
1289 Django to the browser.
1290
1291 .. admonition:: Advanced usage
1292
1293 :class:`StreamingHttpResponse` is somewhat advanced, in that it is
1294 important to know whether you'll be serving your application synchronously
1295 under WSGI or asynchronously under ASGI, and adjust your usage
1296 appropriately.
1297
1298 Please read these notes with care.
1299
1300 An example usage of :class:`StreamingHttpResponse` under WSGI is streaming
1301 content when generating the response would take too long or uses too much
1302 memory. For instance, it's useful for :ref:`generating large CSV files
1303 <streaming-csv-files>`.
1304
1305 There are performance considerations when doing this, though. Django, under
1306 WSGI, is designed for short-lived requests. Streaming responses will tie a
1307 worker process for the entire duration of the response. This may result in poor
1308 performance.
1309
1310 Generally speaking, you would perform expensive tasks outside of the
1311 request-response cycle, rather than resorting to a streamed response.
1312
1313 When serving under ASGI, however, a :class:`StreamingHttpResponse` need not
1314 stop other requests from being served whilst waiting for I/O. This opens up
1315 the possibility of long-lived requests for streaming content and implementing
1316 patterns such as long-polling, and server-sent events.
1317
1318 Even under ASGI note, :class:`StreamingHttpResponse` should only be used in
1319 situations where it is absolutely required that the whole content isn't
1320 iterated before transferring the data to the client. Because the content can't
1321 be accessed, many middleware can't function normally. For example the ``ETag``
1322 and ``Content-Length`` headers can't be generated for streaming responses.
1323
1324 The :class:`StreamingHttpResponse` is not a subclass of :class:`HttpResponse`,
1325 because it features a slightly different API. However, it is almost identical,
1326 with the following notable differences:
1327
1328 * It should be given an iterator that yields bytestrings, :class:`memoryview`,
1329 or strings as content. When serving under WSGI, this should be a sync
1330 iterator. When serving under ASGI, then it should be an async iterator.
1331
1332 * You cannot access its content, except by iterating the response object
1333 itself. This should only occur when the response is returned to the client:
1334 you should not iterate the response yourself.
1335
1336 Under WSGI the response will be iterated synchronously. Under ASGI the
1337 response will be iterated asynchronously. (This is why the iterator type must
1338 match the protocol you're using.)
1339
1340 To avoid a crash, an incorrect iterator type will be mapped to the correct
1341 type during iteration, and a warning will be raised, but in order to do this
1342 the iterator must be fully-consumed, which defeats the purpose of using a
1343 :class:`StreamingHttpResponse` at all.
1344
1345 * It has no ``content`` attribute. Instead, it has a
1346 :attr:`~StreamingHttpResponse.streaming_content` attribute. This can be used
1347 in middleware to wrap the response iterable, but should not be consumed.
1348
1349 * It has no ``text`` attribute, as it would require iterating the response
1350 object.
1351
1352 * You cannot use the file-like object ``tell()`` or ``write()`` methods.
1353 Doing so will raise an exception.
1354
1355 The :class:`HttpResponseBase` base class is common between
1356 :class:`HttpResponse` and :class:`StreamingHttpResponse`.
1357
1358 Attributes
1359 ----------
1360
1361 .. attribute:: StreamingHttpResponse.streaming_content
1362
1363 An iterator of the response content, bytestring encoded according to
1364 :attr:`HttpResponse.charset`.
1365
1366 .. attribute:: StreamingHttpResponse.status_code
1367
1368 The :rfc:`HTTP status code <9110#section-15>` for the response.
1369
1370 Unless :attr:`reason_phrase` is explicitly set, modifying the value of
1371 ``status_code`` outside the constructor will also modify the value of
1372 ``reason_phrase``.
1373
1374 .. attribute:: StreamingHttpResponse.reason_phrase
1375
1376 The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
1377 <9110#section-15.1>` default reason phrases.
1378
1379 Unless explicitly set, ``reason_phrase`` is determined by the value of
1380 :attr:`status_code`.
1381
1382 .. attribute:: StreamingHttpResponse.streaming
1383
1384 This is always ``True``.
1385
1386 .. attribute:: StreamingHttpResponse.is_async
1387
1388 Boolean indicating whether :attr:`StreamingHttpResponse.streaming_content`
1389 is an asynchronous iterator or not.
1390
1391 This is useful for middleware needing to wrap
1392 :attr:`StreamingHttpResponse.streaming_content`.
1393
1394 .. _request-response-streaming-disconnect:
1395
1396 Handling disconnects
1397 --------------------
1398
1399 If the client disconnects during a streaming response, Django will cancel the
1400 coroutine that is handling the response. If you want to clean up resources
1401 manually, you can do so by catching the ``asyncio.CancelledError``::
1402
1403 async def streaming_response():
1404 try:
1405 # Do some work here
1406 async for chunk in my_streaming_iterator():
1407 yield chunk
1408 except asyncio.CancelledError:
1409 # Handle disconnect
1410 ...
1411 raise
1412
1413
1414 async def my_streaming_view(request):
1415 return StreamingHttpResponse(streaming_response())
1416
1417 This example only shows how to handle client disconnection while the response
1418 is streaming. If you perform long-running operations in your view before
1419 returning the ``StreamingHttpResponse`` object, then you may also want to
1420 :ref:`handle disconnections in the view <async-handling-disconnect>` itself.
1421
1422 ``FileResponse`` objects
1423 ========================
1424
1425 .. class:: FileResponse(open_file, as_attachment=False, filename='', **kwargs)
1426
1427 :class:`FileResponse` is a subclass of :class:`StreamingHttpResponse`
1428 optimized for binary files. It uses :pep:`wsgi.file_wrapper
1429 <3333#optional-platform-specific-file-handling>` if provided by the wsgi
1430 server, otherwise it streams the file out in small chunks.
1431
1432 If ``as_attachment=True``, the ``Content-Disposition`` header is set to
1433 ``attachment``, which asks the browser to offer the file to the user as a
1434 download. Otherwise, a ``Content-Disposition`` header with a value of
1435 ``inline`` (the browser default) will be set only if a filename is
1436 available.
1437
1438 If ``open_file`` doesn't have a name or if the name of ``open_file`` isn't
1439 appropriate, provide a custom file name using the ``filename`` parameter.
1440 Note that if you pass a file-like object like ``io.BytesIO``, it's your
1441 task to ``seek()`` it before passing it to ``FileResponse``.
1442
1443 The ``Content-Length`` header is automatically set when it can be guessed
1444 from the content of ``open_file``.
1445
1446 The ``Content-Type`` header is automatically set when it can be guessed
1447 from the ``filename``, or the name of ``open_file``.
1448
1449 ``FileResponse`` accepts any file-like object with binary content, for example
1450 a file open in binary mode like so:
1451
1452 .. code-block:: pycon
1453
1454 >>> from django.http import FileResponse
1455 >>> response = FileResponse(open("myfile.png", "rb"))
1456
1457 The file will be closed automatically, so don't open it with a context manager.
1458
1459 .. admonition:: Use under ASGI
1460
1461 Python's file API is synchronous. This means that the file must be fully
1462 consumed in order to be served under ASGI.
1463
1464 In order to stream a file asynchronously you need to use a third-party
1465 package that provides an asynchronous file API, such as `aiofiles
1466 <https://github.com/Tinche/aiofiles>`_.
1467
1468 Methods
1469 -------
1470
1471 .. method:: FileResponse.set_headers(open_file)
1472
1473 This method is automatically called during the response initialization and
1474 set various headers (``Content-Length``, ``Content-Type``, and
1475 ``Content-Disposition``) depending on ``open_file``.
1476
1477 ``HttpResponseBase`` class
1478 ==========================
1479
1480 .. class:: HttpResponseBase
1481
1482 The :class:`HttpResponseBase` class is common to all Django responses.
1483 It should not be used to create responses directly, but it can be
1484 useful for type-checking.