| 837 | |
| 838 | |
| 839 | class HTTPConnection: |
| 840 | |
| 841 | _http_vsn = 11 |
| 842 | _http_vsn_str = 'HTTP/1.1' |
| 843 | |
| 844 | response_class = HTTPResponse |
| 845 | default_port = HTTP_PORT |
| 846 | auto_open = 1 |
| 847 | debuglevel = 0 |
| 848 | |
| 849 | @staticmethod |
| 850 | def _is_textIO(stream): |
| 851 | """Test whether a file-like object is a text or a binary stream. |
| 852 | """ |
| 853 | return isinstance(stream, io.TextIOBase) |
| 854 | |
| 855 | @staticmethod |
| 856 | def _get_content_length(body, method): |
| 857 | """Get the content-length based on the body. |
| 858 | |
| 859 | If the body is None, we set Content-Length: 0 for methods that expect |
| 860 | a body (RFC 7230, Section 3.3.2). We also set the Content-Length for |
| 861 | any method if the body is a str or bytes-like object and not a file. |
| 862 | """ |
| 863 | if body is None: |
| 864 | # do an explicit check for not None here to distinguish |
| 865 | # between unset and set but empty |
| 866 | if method.upper() in _METHODS_EXPECTING_BODY: |
| 867 | return 0 |
| 868 | else: |
| 869 | return None |
| 870 | |
| 871 | if hasattr(body, 'read'): |
| 872 | # file-like object. |
| 873 | return None |
| 874 | |
| 875 | try: |
| 876 | # does it implement the buffer protocol (bytes, bytearray, array)? |
| 877 | mv = memoryview(body) |
| 878 | return mv.nbytes |
| 879 | except TypeError: |
| 880 | pass |
| 881 | |
| 882 | if isinstance(body, str): |
| 883 | return len(body) |
| 884 | |
| 885 | return None |
| 886 | |
| 887 | def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, |
| 888 | source_address=None, blocksize=8192): |
| 889 | self.timeout = timeout |
| 890 | self.source_address = source_address |
| 891 | self.blocksize = blocksize |
| 892 | self.sock = None |
| 893 | self._buffer = [] |
| 894 | self.__response = None |
| 895 | self.__state = _CS_IDLE |
| 896 | self._method = None |