MCPcopy
hub / github.com/django/django / _convert_to_charset

Method _convert_to_charset

django/http/response.py:48–85  ·  view source on GitHub ↗

Convert headers key/value to ascii/latin-1 native strings. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and `value` can't be represented in the given charset, apply MIME-encoding.

(self, value, charset, mime_encode=False)

Source from the content-addressed store, hash-verified

46 self[header] = value
47
48 def _convert_to_charset(self, value, charset, mime_encode=False):
49 """
50 Convert headers key/value to ascii/latin-1 native strings.
51 `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
52 `value` can't be represented in the given charset, apply MIME-encoding.
53 """
54 try:
55 if isinstance(value, str):
56 # Ensure string is valid in given charset
57 value.encode(charset)
58 elif isinstance(value, bytes):
59 # Convert bytestring using given charset
60 value = value.decode(charset)
61 else:
62 value = str(value)
63 # Ensure string is valid in given charset.
64 value.encode(charset)
65 if "\n" in value or "\r" in value:
66 raise BadHeaderError(
67 f"Header values can't contain newlines (got {value!r})"
68 )
69 except UnicodeError as e:
70 # Encoding to a string of the specified charset failed, but we
71 # don't know what type that value was, or if it contains newlines,
72 # which we may need to check for before sending it to be
73 # encoded for multiple character sets.
74 if (isinstance(value, bytes) and (b"\n" in value or b"\r" in value)) or (
75 isinstance(value, str) and ("\n" in value or "\r" in value)
76 ):
77 raise BadHeaderError(
78 f"Header values can't contain newlines (got {value!r})"
79 ) from e
80 if mime_encode:
81 value = Header(value, "utf-8", maxlinelen=sys.maxsize).encode()
82 else:
83 e.reason += ", HTTP response headers must be in %s format" % charset
84 raise
85 return value
86
87 def __delitem__(self, key):
88 self.pop(key)

Callers 1

__setitem__Method · 0.95

Calls 3

BadHeaderErrorClass · 0.85
encodeMethod · 0.45
decodeMethod · 0.45

Tested by

no test coverage detected