Get the content-length based on the body. If the body is None, we set Content-Length: 0 for methods that expect a body (RFC 7230, Section 3.3.2). We also set the Content-Length for any method if the body is a str or bytes-like object and not a file.
(body, method)
| 857 | |
| 858 | @staticmethod |
| 859 | def _get_content_length(body, method): |
| 860 | """Get the content-length based on the body. |
| 861 | |
| 862 | If the body is None, we set Content-Length: 0 for methods that expect |
| 863 | a body (RFC 7230, Section 3.3.2). We also set the Content-Length for |
| 864 | any method if the body is a str or bytes-like object and not a file. |
| 865 | """ |
| 866 | if body is None: |
| 867 | # do an explicit check for not None here to distinguish |
| 868 | # between unset and set but empty |
| 869 | if method.upper() in _METHODS_EXPECTING_BODY: |
| 870 | return 0 |
| 871 | else: |
| 872 | return None |
| 873 | |
| 874 | if hasattr(body, 'read'): |
| 875 | # file-like object. |
| 876 | return None |
| 877 | |
| 878 | try: |
| 879 | # does it implement the buffer protocol (bytes, bytearray, array)? |
| 880 | mv = memoryview(body) |
| 881 | return mv.nbytes |
| 882 | except TypeError: |
| 883 | pass |
| 884 | |
| 885 | if isinstance(body, str): |
| 886 | return len(body) |
| 887 | |
| 888 | return None |
| 889 | |
| 890 | def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, |
| 891 | source_address=None, blocksize=8192, *, max_response_headers=None): |