Turn a value into a bytestring encoded in the output charset.
(self, value)
| 308 | # Common methods used by subclasses |
| 309 | |
| 310 | def make_bytes(self, value): |
| 311 | """Turn a value into a bytestring encoded in the output charset.""" |
| 312 | # Per PEP 3333, this response body must be bytes. To avoid returning |
| 313 | # an instance of a subclass, this function returns `bytes(value)`. |
| 314 | # This doesn't make a copy when `value` already contains bytes. |
| 315 | |
| 316 | # Handle string types -- we can't rely on force_bytes here because: |
| 317 | # - Python attempts str conversion first |
| 318 | # - when self._charset != 'utf-8' it re-encodes the content |
| 319 | if isinstance(value, (bytes, memoryview)): |
| 320 | return bytes(value) |
| 321 | if isinstance(value, str): |
| 322 | return bytes(value.encode(self.charset)) |
| 323 | # Handle non-string types. |
| 324 | return str(value).encode(self.charset) |
| 325 | |
| 326 | # These methods partially implement the file-like object interface. |
| 327 | # See https://docs.python.org/library/io.html#io.IOBase |