MCPcopy
hub / github.com/django/django / set_headers

Method set_headers

django/http/response.py:577–629  ·  view source on GitHub ↗

Set some common response headers (Content-Length, Content-Type, and Content-Disposition) based on the `filelike` response content.

(self, filelike)

Source from the content-addressed store, hash-verified

575 super()._set_streaming_content(value)
576
577 def set_headers(self, filelike):
578 """
579 Set some common response headers (Content-Length, Content-Type, and
580 Content-Disposition) based on the `filelike` response content.
581 """
582 filename = getattr(filelike, "name", "")
583 filename = filename if isinstance(filename, str) else ""
584 seekable = hasattr(filelike, "seek") and (
585 not hasattr(filelike, "seekable") or filelike.seekable()
586 )
587 if hasattr(filelike, "tell"):
588 if seekable:
589 initial_position = filelike.tell()
590 filelike.seek(0, io.SEEK_END)
591 self.headers["Content-Length"] = filelike.tell() - initial_position
592 filelike.seek(initial_position)
593 elif hasattr(filelike, "getbuffer"):
594 self.headers["Content-Length"] = (
595 filelike.getbuffer().nbytes - filelike.tell()
596 )
597 elif os.path.exists(filename):
598 self.headers["Content-Length"] = (
599 os.path.getsize(filename) - filelike.tell()
600 )
601 elif seekable:
602 self.headers["Content-Length"] = sum(
603 iter(lambda: len(filelike.read(self.block_size)), 0)
604 )
605 filelike.seek(-int(self.headers["Content-Length"]), io.SEEK_END)
606
607 filename = os.path.basename(self.filename or filename)
608 if self._no_explicit_content_type:
609 if filename:
610 content_type, encoding = mimetypes.guess_type(filename)
611 # Encoding isn't set to prevent browsers from automatically
612 # uncompressing files.
613 content_type = {
614 "br": "application/x-brotli",
615 "bzip2": "application/x-bzip",
616 "compress": "application/x-compress",
617 "gzip": "application/gzip",
618 "xz": "application/x-xz",
619 }.get(encoding, content_type)
620 self.headers["Content-Type"] = (
621 content_type or "application/octet-stream"
622 )
623 else:
624 self.headers["Content-Type"] = "application/octet-stream"
625
626 if content_disposition := content_disposition_header(
627 self.as_attachment, filename
628 ):
629 self.headers["Content-Disposition"] = content_disposition
630
631
632class HttpResponseRedirectBase(HttpResponse):

Callers 1

Calls 7

seekMethod · 0.80
seekableMethod · 0.45
tellMethod · 0.45
existsMethod · 0.45
readMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected