https://github.com/python/cpython/commit/9736a841a1f11065aeb7792cd5f1b00ea7b0c893
commit: 9736a841a1f11065aeb7792cd5f1b00ea7b0c893
branch: main
author: IngridMorstrad <[email protected]>
committer: orsenthil <[email protected]>
date: 2026-11-12T06:45:13Z
summary:

gh-42550: Add 'Expect: 100-Continue' support to httplib (#133276)

* Add 'Expect: 100-Continue' support to httplib

Previously, http.client would always send content body immediately and ignore 
any 100 responses. This change makes HTTPClient.request() wait for a `Continue` 
response if the `Expect: 100-Continue` header is set, and adds a parameter to 
HTTPClient.getresponse() that will cause it to return 100 responses instead of 
eating them.

---------

Co-authored-by: Peter Bierma <[email protected]>
Co-authored-by: Senthil Kumaran <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-09-27-13-04-02.gh-issue-42550.sqYlvB.rst
M Doc/library/http.client.rst
M Doc/whatsnew/3.16.rst
M Lib/http/client.py
M Lib/test/test_httplib.py
M Misc/ACKS

diff --git a/Doc/library/http.client.rst b/Doc/library/http.client.rst
index 22448c14f7a188..20fd357c56ac3e 100644
--- a/Doc/library/http.client.rst
+++ b/Doc/library/http.client.rst
@@ -282,7 +282,7 @@ HTTPConnection Objects
 
 
 .. method:: HTTPConnection.request(method, url, body=None, headers={}, *, \
-            encode_chunked=False)
+            encode_chunked=False, continue_timeout=2.5)
 
    This will send a request to the server using the HTTP request
    method *method* and the request URI *url*. The provided *url* must be
@@ -358,11 +358,33 @@ HTTPConnection Objects
       No attempt is made to determine the Content-Length for file
       objects.
 
-.. method:: HTTPConnection.getresponse()
+   .. versionchanged:: next
+      The *continue_timeout* parameter was added.
+
+      If the headers include ``Expect: 100-Continue`` and *body* is set, the
+      body will not be sent until either a ``100 Continue`` response is
+      received from the server or *continue_timeout* seconds have elapsed; if a
+      response code other than 100 is received, the body will not be sent at 
all.
+
+      *continue_timeout* value must be greater than zero, otherwise
+      :exc:`ValueError` is raised.
+
+.. method:: HTTPConnection.getresponse(support_continue=False)
 
    Should be called after a request is sent to get the response from the 
server.
    Returns an :class:`HTTPResponse` instance.
 
+   By default, ``100 Continue`` responses are skipped and the method returns
+   the first response with a status other than 100.  If *support_continue*
+   is true, a ``100 Continue`` response is returned to the caller, which must
+   then send the request body and call :meth:`getresponse` again to obtain
+   the final response.
+
+   .. note::
+
+      The whole response must be read before a new request can be sent to
+      the server.
+
    .. versionchanged:: 3.5
       If a :exc:`ConnectionError` or subclass is raised, the
       :class:`HTTPConnection` object will be ready to reconnect when
@@ -372,6 +394,10 @@ HTTPConnection Objects
       socket. Instead the caller is responsible to call :meth:`close` on the
       existing connection.
 
+   .. versionchanged:: next
+      Added the *support_continue* parameter. (In prior versions
+      a ``Continue`` response was always ignored.)
+
 
 .. method:: HTTPConnection.set_debuglevel(level)
 
@@ -470,7 +496,8 @@ also send your request step by step, by using the four 
functions below.
 
 
 .. method:: HTTPConnection.putrequest(method, url, skip_host=False, \
-                                      skip_accept_encoding=False)
+                                      skip_accept_encoding=False, \
+                                      continue_timeout=2.5)
 
    This should be the first call after the connection to the server has been
    made. It sends a line to the server consisting of the *method* string,
@@ -479,6 +506,14 @@ also send your request step by step, by using the four 
functions below.
    additional content encodings), specify *skip_host* or *skip_accept_encoding*
    with non-False values.
 
+   If an ``Expect: 100-Continue`` header is sent, the optional
+   *continue_timeout* parameter sets how many seconds the client will wait for
+   a ``100 Continue`` response before sending the message body,    It must be
+   greater than zero, otherwise :exc:`ValueError` is raised.
+
+   .. versionchanged:: next
+      *continue_timeout* parameter was added.
+
 
 .. method:: HTTPConnection.putheader(header, argument[, ...])
 
@@ -492,7 +527,12 @@ also send your request step by step, by using the four 
functions below.
 
    Send a blank line to the server, signalling the end of the headers. The
    optional *message_body* argument can be used to pass a message body
-   associated with the request.
+   associated with the request. If a body is provided and an
+   ``Expect: 100-Continue`` header has been sent, the body will not be sent
+   until a ``100 Continue`` response is received from the server; if another
+   response code is received, the body is not sent at all.  If no response
+   is received within the *continue_timeout* given to :meth:`putrequest`,
+   the body will be sent regardless.
 
    If *encode_chunked* is ``True``, the result of each iteration of
    *message_body* will be chunk-encoded as specified in :rfc:`7230`,
@@ -513,6 +553,12 @@ also send your request step by step, by using the four 
functions below.
    .. versionchanged:: 3.6
       Added chunked encoding support and the *encode_chunked* parameter.
 
+   .. versionchanged:: next
+      If an ``Expect: 100-Continue`` header has been sent, the body will not be
+      sent until a ``100 Continue`` response is received from the server, or a
+      contine_timeout has elapsed. If the response code is not 100, the body
+      will not be sent at all.
+
 
 .. method:: HTTPConnection.send(data)
 
@@ -691,6 +737,46 @@ method attribute. Here is an example session that uses the 
``PUT`` method::
     >>> print(response.status, response.reason)
     200 OK
 
+Conditional transmission of the body is supported when an ``Expect: 
100-Continue``
+header is set. To use this in a simple case, just set the header, and
+optionally the time for which the client should wait for a ``100 Continue``
+response before sending the body regardless::
+
+    >>> import http.client
+    >>> BODY = "***filecontents***"
+    >>> conn = http.client.HTTPConnection("localhost", 8080)
+    >>> conn.request("PUT", "/file", BODY, headers={'Expect': '100-Continue'},
+    ...              continue_timeout=1.0)
+    >>> response = conn.getresponse()
+    >>> # You will not see the '100' response, as it is handled internally
+    >>> print(response.status, response.reason)
+    200, OK
+
+Here is a more complex example in which we manually check the response and
+decide whether to send the body. This may be useful if the body must be
+generated by some resource-intensive process which should be skipped if the
+server will not accept it.  *continue_timeout* does not apply here, so this
+should only be used with servers known to support ``Expect: 100-Continue``;
+otherwise :meth:`~HTTPConnection.getresponse` may block until the
+connection's *timeout* expires. ::
+
+    >>> import http.client
+    >>> conn = http.client.HTTPConnection("localhost", 8080)
+    >>> conn.putrequest("PUT", "/file")
+    >>> conn.putheader('Expect', '100-Continue')
+    >>> # Assuming you know in advance what the length will be
+    >>> # If not, you will need to encode it as chunked
+    >>> conn.putheader('Content-Length', '42')
+    >>> conn.endheaders()
+    >>> response = conn.getresponse(support_continue=True)
+    >>> print(response.status, response.reason)
+    100, Continue
+    >>> BODY = resource_intensive_calculation()
+    >>> conn.send(BODY)
+    >>> response = conn.getresponse()
+    >>> print(response.status, response.reason)
+    200, OK
+
 .. _httpmessage-objects:
 
 HTTPMessage Objects
diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst
index da81d8513da99d..f86a6ec69172d8 100644
--- a/Doc/whatsnew/3.16.rst
+++ b/Doc/whatsnew/3.16.rst
@@ -511,6 +511,17 @@ gzip
 http.client
 -----------
 
+* :class:`~http.client.HTTPConnection` now honors an ``Expect: 100-Continue``
+  request header: the request body is sent only after the server responds
+  with ``100 Continue``, or once the new *continue_timeout* of
+  :meth:`~http.client.HTTPConnection.request` and
+  :meth:`~http.client.HTTPConnection.putrequest` expires.  If the server
+  responds with a final status instead, the body is not sent.
+  :meth:`~http.client.HTTPConnection.getresponse` gains a *support_continue*
+  parameter to return ``100 Continue`` responses to the caller.
+  (Contributed by Ashwin Menon, Tim Bartlett and Senthil Kumaran in
+  :gh:`42550`.)
+
 * Add the :exc:`~http.client.ProxyTunnelError` exception, a subclass of
   :exc:`OSError` raised when a proxy rejects the CONNECT request sent for
   :meth:`~http.client.HTTPConnection.set_tunnel`.  It exposes the status
diff --git a/Lib/http/client.py b/Lib/http/client.py
index 96f266f32346ab..4bdb8f72f979b1 100644
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -75,11 +75,17 @@
 import http
 import io
 import re
+import select
 import socket
 import sys
 import collections.abc
 from urllib.parse import urlsplit
 
+try:
+    import ssl
+except ImportError:
+    ssl = None
+
 # HTTPMessage, parse_headers(), and the HTTP status code constants are
 # intentionally omitted for simplicity
 __all__ = ["HTTPResponse", "HTTPConnection",
@@ -119,6 +125,10 @@
 # timeout window.
 _MAXINTERIMRESPONSES = 100
 
+# default number of seconds to wait for a "100 Continue" response before
+# sending the body of a request with an "Expect: 100-Continue" header.
+_DEFAULT_CONTINUE_TIMEOUT = 2.5
+
 # Data larger than this will be read in chunks, to prevent extreme
 # overallocation.
 _MIN_READ_BUF_SIZE = 1 << 20
@@ -341,7 +351,7 @@ def _read_status(self):
             raise BadStatusLine(line)
         return version, status, reason
 
-    def begin(self, *, _max_headers=None):
+    def begin(self, *, support_continue=False, _max_headers=None):
         if self.headers is not None:
             # we've already started reading the response
             return
@@ -354,8 +364,13 @@ def begin(self, *, _max_headers=None):
         # read until we get a non-100 response
         for _ in range(_MAXINTERIMRESPONSES):
             version, status, reason = self._read_status()
-            if status != CONTINUE:
+
+            if support_continue or status != CONTINUE:
+                # This is the response to return to the caller: either a
+                # final response (status != CONTINUE), or a 100 Continue
+                # the caller asked to see.
                 break
+
             # skip the header from the 100 response
             skipped_headers = _read_headers(self.fp, _max_headers)
             if self.debuglevel > 0:
@@ -929,7 +944,9 @@ def __init__(self, host, port=None, 
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
         self.sock = None
         self._buffer = []
         self.__response = None
+        self.__pending_response = None
         self.__state = _CS_IDLE
+        self._continue_timeout = _DEFAULT_CONTINUE_TIMEOUT
         self._method = None
         self._tunnel_host = None
         self._tunnel_port = None
@@ -941,9 +958,10 @@ def __init__(self, host, port=None, 
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
 
         self._validate_host(self.host)
 
-        # This is stored as an instance variable to allow unit
-        # tests to replace it with a suitable mockup
+        # These are stored as instance variables to allow unit
+        # tests to replace them with a suitable mockup
         self._create_connection = socket.create_connection
+        self._select = select.select
 
     def set_tunnel(self, host, port=None, headers=None):
         """Set up host and port for HTTP CONNECT tunnelling.
@@ -1089,6 +1107,10 @@ def close(self):
                 self.sock = None
                 sock.close()   # close it manually... there may be other refs
         finally:
+            pending_response = self.__pending_response
+            if pending_response:
+                self.__pending_response = None
+                pending_response.close()
             response = self.__response
             if response:
                 self.__response = None
@@ -1149,7 +1171,9 @@ def _read_readable(self, readable):
                 datablock = datablock.encode("iso-8859-1")
             yield datablock
 
-    def _send_output(self, message_body=None, encode_chunked=False):
+    def _send_output(self, message_body=None, encode_chunked=False,
+                     expect_continue=False,
+                     continue_timeout=_DEFAULT_CONTINUE_TIMEOUT):
         """Send the currently buffered request and clear the buffer.
 
         Appends an extra \\r\\n to the buffer.
@@ -1161,6 +1185,34 @@ def _send_output(self, message_body=None, 
encode_chunked=False):
         self.send(msg)
 
         if message_body is not None:
+            if expect_continue and not self.__response:
+                # For a TLS socket, check for already decrypted data in the
+                # internal buffer of the SSLSocket.
+                if (ssl is not None and isinstance(self.sock, ssl.SSLSocket)
+                        and self.sock.pending() > 0):
+                    read_ready = True
+                else:
+                    read_ready, _, _ = self._select([self.sock], [], [],
+                                                    continue_timeout)
+                if read_ready:
+                    if self.debuglevel > 0:
+                        response = self.response_class(self.sock,
+                                                       self.debuglevel,
+                                                       method=self._method)
+                    else:
+                        response = self.response_class(self.sock,
+                                                       method=self._method)
+                    if self.max_response_headers is None:
+                        response.begin(support_continue=True)
+                    else:
+                        response.begin(
+                            support_continue=True,
+                            _max_headers=self.max_response_headers)
+                    if response.code != CONTINUE:
+                        # Break without sending the body
+                        self.__pending_response = response
+                        return
+                    response.close()
 
             # create a consistent interface to message_body
             if hasattr(message_body, 'read'):
@@ -1204,7 +1256,8 @@ def _send_output(self, message_body=None, 
encode_chunked=False):
                 self.send(b'0\r\n\r\n')
 
     def putrequest(self, method, url, skip_host=False,
-                   skip_accept_encoding=False):
+                   skip_accept_encoding=False,
+                   continue_timeout=_DEFAULT_CONTINUE_TIMEOUT):
         """Send a request to the server.
 
         'method' specifies an HTTP request method, e.g. 'GET'.
@@ -1213,12 +1266,14 @@ def putrequest(self, method, url, skip_host=False,
         'skip_accept_encoding' if True does not add automatically an
            'Accept-Encoding:' header
         """
+        if continue_timeout <= 0.0:
+            raise ValueError("continue_timeout must be greater than 0")
+        self._continue_timeout = continue_timeout
 
         # if a prior response has been completed, then forget about it.
         if self.__response and self.__response.isclosed():
             self.__response = None
 
-
         # in certain cases, we cannot issue another request on this connection.
         # this occurs when:
         #   1) we are in the process of sending a request.   (_CS_REQ_STARTED)
@@ -1398,14 +1453,31 @@ def endheaders(self, message_body=None, *, 
encode_chunked=False):
             self.__state = _CS_REQ_SENT
         else:
             raise CannotSendHeader()
-        self._send_output(message_body, encode_chunked=encode_chunked)
+
+        expect_continue = False
+        if message_body is not None and not self.__response:
+            prefix = b'expect:'
+            for line in self._buffer:
+                if line.lower().startswith(prefix):
+                    value = line[len(prefix):].strip().lower()
+                    expect_continue = value == b'100-continue'
+                    break
+
+        self._send_output(message_body, encode_chunked=encode_chunked,
+                          expect_continue=expect_continue,
+                          continue_timeout=self._continue_timeout)
 
     def request(self, method, url, body=None, headers={}, *,
-                encode_chunked=False):
+                encode_chunked=False,
+                continue_timeout=_DEFAULT_CONTINUE_TIMEOUT):
         """Send a complete request to the server."""
-        self._send_request(method, url, body, headers, encode_chunked)
+        if continue_timeout <= 0.0:
+            raise ValueError("continue_timeout must be greater than 0")
+        self._send_request(method, url, body, headers, encode_chunked,
+                           continue_timeout)
 
-    def _send_request(self, method, url, body, headers, encode_chunked):
+    def _send_request(self, method, url, body, headers, encode_chunked,
+                      continue_timeout):
         # Honor explicitly requested Host: and Accept-Encoding: headers.
         header_names = frozenset(k.lower() for k in headers)
         skips = {}
@@ -1414,7 +1486,8 @@ def _send_request(self, method, url, body, headers, 
encode_chunked):
         if 'accept-encoding' in header_names:
             skips['skip_accept_encoding'] = 1
 
-        self.putrequest(method, url, **skips)
+        self.putrequest(method, url, **skips,
+                        continue_timeout=continue_timeout)
 
         # chunked encoding will happen if HTTP/1.1 is used and either
         # the caller passes encode_chunked=True or the following
@@ -1451,11 +1524,13 @@ def _send_request(self, method, url, body, headers, 
encode_chunked):
             body = _encode(body, 'body')
         self.endheaders(body, encode_chunked=encode_chunked)
 
-    def getresponse(self):
+    def getresponse(self, support_continue=False):
         """Get the response from the server.
 
         If the HTTPConnection is in the correct state, returns an
-        instance of HTTPResponse.
+        instance of HTTPResponse or of whatever object is returned by the
+        response_class variable. The connection will wait for a response other
+        than code 100 ('Continue') unless support_continue is set to True.
 
         If a request has not been sent or if a previous response has
         not be handled, ResponseNotReady is raised.  If the HTTP
@@ -1486,7 +1561,10 @@ def getresponse(self):
         if self.__state != _CS_REQ_SENT or self.__response:
             raise ResponseNotReady(self.__state)
 
-        if self.debuglevel > 0:
+        if self.__pending_response:
+            response = self.__pending_response
+            self.__pending_response = None
+        elif self.debuglevel > 0:
             response = self.response_class(self.sock, self.debuglevel,
                                            method=self._method)
         else:
@@ -1495,32 +1573,32 @@ def getresponse(self):
         try:
             try:
                 if self.max_response_headers is None:
-                    response.begin()
+                    response.begin(support_continue=support_continue)
                 else:
-                    response.begin(_max_headers=self.max_response_headers)
+                    response.begin(support_continue=support_continue,
+                                   _max_headers=self.max_response_headers)
             except ConnectionError:
                 self.close()
                 raise
             assert response.will_close != _UNKNOWN
-            self.__state = _CS_IDLE
+            if response.code != 100:
+                # Code 100 is effectively 'not a response' for this purpose
+                self.__state = _CS_IDLE
 
-            if response.will_close:
-                # this effectively passes the connection to the response
-                self.close()
-            else:
-                # remember this, so we can tell when it is complete
-                self.__response = response
+                if response.will_close:
+                    # this effectively passes the connection to the response
+                    self.close()
+                else:
+                    # remember this, so we can tell when it is complete
+                    self.__response = response
 
             return response
         except:
             response.close()
             raise
 
-try:
-    import ssl
-except ImportError:
-    pass
-else:
+if ssl is not None:
+
     class HTTPSConnection(HTTPConnection):
         "This class allows communication via SSL."
 
diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py
index 57eedee25a89e0..849c44e17aab0a 100644
--- a/Lib/test/test_httplib.py
+++ b/Lib/test/test_httplib.py
@@ -7,6 +7,7 @@
 import pickle
 import array
 import re
+import select
 import socket
 import threading
 
@@ -17,6 +18,7 @@
 from test import support
 from test.support import os_helper
 from test.support import socket_helper
+from test.support import threading_helper
 
 support.requires_working_socket(module=True)
 
@@ -126,6 +128,7 @@ def __init__(self, *args):
         super().__init__('example.com')
         self.fake_socket_args = args
         self._create_connection = self.create_connection
+        self._select = self.fake_select
 
     def connect(self):
         """Count the number of times connect() is invoked"""
@@ -135,6 +138,23 @@ def connect(self):
     def create_connection(self, *pos, **kw):
         return FakeSocket(*self.fake_socket_args)
 
+    @staticmethod
+    def fake_select(rlist, wlist, xlist, timeout=None):
+        """Real select.select() won't work on our fake socket"""
+        # Only needs to support read select for current tests
+        ret = []
+        for r in rlist:
+            assert isinstance(r, FakeSocket)
+            if r.data and not hasattr(r, 'file'):
+                # Has data to read, hasn't called makefile() yet
+                ret.append(r)
+            elif getattr(r, 'file', None) and not r.file_closed:
+                if r.file.read(1):
+                    r.file.seek(r.file.tell() - 1)
+                    ret.append(r)
+        return ret, [], []
+
+
 class HeaderTests(TestCase):
     def test_auto_headers(self):
         # Some headers are added automatically, but should not be added by
@@ -2504,6 +2524,260 @@ def test_binary_file_body(self):
             self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
 
 
+class ExpectContinueTests(TestCase):
+
+    def test_data_sent_on_continue(self):
+        # Prior versions would pass this too, as they send body immediately
+        # and ignore the Continue, but make sure it still behaves as expected.
+        conn = FakeSocketHTTPConnection(
+            b'HTTP/1.1 100 Continue\r\n'
+            b'\r\n'
+            b'HTTP/1.1 200 OK\r\n'
+            b'Content-Length: 0\r\n'
+            b'\r\n'
+        )
+        conn.request('PUT', '/', headers={'Expect': '100-continue'},
+                     body=b'Body content')
+        resp = conn.getresponse()
+        self.assertEqual(resp.code, 200)
+        self.assertIn(b'Expect: 100-continue', conn.sock.data)
+        self.assertIn(b'Body content', conn.sock.data)
+
+    def test_data_not_sent_on_error(self):
+        conn = FakeSocketHTTPConnection(
+            b'HTTP/1.1 429 Too Many Requests\r\n'
+            b'Content-Length: 0\r\n'
+            b'\r\n'
+        )
+        conn.request('PUT', '/', headers={'Expect': '100-continue'},
+                     body=b'Body content')
+        resp = conn.getresponse()
+        self.assertEqual(resp.code, 429)
+        self.assertIn(b'Expect: 100-continue', conn.sock.data)
+        self.assertNotIn(b'Body content', conn.sock.data)
+
+    def test_request_continue_timeout(self):
+        conn = FakeSocketHTTPConnection(
+            b'HTTP/1.1 100 Continue\r\n'
+            b'\r\n'
+            b'HTTP/1.1 200 OK\r\n'
+            b'Content-Length: 0\r\n'
+            b'\r\n'
+        )
+        conn._select = mock.Mock(wraps=conn.fake_select)
+        conn.request('PUT', '/', headers={'Expect': '100-continue'},
+                     body=b'Body content', continue_timeout=0.25)
+        conn._select.assert_called_once_with([conn.sock], [], [], 0.25)
+        self.assertEqual(conn.getresponse().code, 200)
+
+    def test_putrequest_continue_timeout(self):
+        conn = FakeSocketHTTPConnection(
+            b'HTTP/1.1 100 Continue\r\n'
+            b'\r\n'
+            b'HTTP/1.1 200 OK\r\n'
+            b'Content-Length: 0\r\n'
+            b'\r\n'
+        )
+        conn._select = mock.Mock(wraps=conn.fake_select)
+        conn.putrequest('PUT', '/', continue_timeout=0.25)
+        conn.putheader('Expect', '100-continue')
+        conn.putheader('Content-Length', '12')
+        conn.endheaders(b'Body content')
+        conn._select.assert_called_once_with([conn.sock], [], [], 0.25)
+        self.assertIn(b'Body content', conn.sock.data)
+        self.assertEqual(conn.getresponse().code, 200)
+
+    def test_invalid_continue_timeout(self):
+        conn = FakeSocketHTTPConnection(b'')
+        for timeout in (0, -1):
+            with self.subTest(timeout=timeout):
+                with self.assertRaises(ValueError):
+                    conn.request('PUT', '/', body=b'Body content',
+                                 continue_timeout=timeout)
+                with self.assertRaises(ValueError):
+                    conn.putrequest('PUT', '/', continue_timeout=timeout)
+
+    @unittest.skipUnless(hasattr(client, 'HTTPSConnection'),
+                         'ssl support required')
+    def test_https_pending_data_skips_select(self):
+        # Data already decrypted and buffered in the SSLSocket is not
+        # visible to select(), so it must be checked with pending().
+        class FakeSSLSocket(FakeSocket):
+            def pending(self):
+                return len(self.text)
+
+        conn = client.HTTPSConnection('example.com')
+        conn.sock = FakeSSLSocket(
+            b'HTTP/1.1 417 Expectation Failed\r\n'
+            b'Content-Length: 0\r\n'
+            b'\r\n'
+        )
+        conn._select = mock.Mock(side_effect=AssertionError('select called'))
+        with mock.patch.object(client, 'ssl',
+                               mock.Mock(SSLSocket=FakeSSLSocket)):
+            conn.request('PUT', '/', headers={'Expect': '100-continue'},
+                         body=b'Body content')
+        conn._select.assert_not_called()
+        self.assertEqual(conn.getresponse().code, 417)
+        self.assertNotIn(b'Body content', conn.sock.data)
+
+    @unittest.skipUnless(hasattr(client, 'HTTPSConnection'),
+                         'ssl support required')
+    def test_https_no_pending_data_uses_select(self):
+        class FakeSSLSocket(FakeSocket):
+            def pending(self):
+                return 0
+
+        conn = client.HTTPSConnection('example.com')
+        conn.sock = FakeSSLSocket(
+            b'HTTP/1.1 100 Continue\r\n'
+            b'\r\n'
+            b'HTTP/1.1 200 OK\r\n'
+            b'Content-Length: 0\r\n'
+            b'\r\n'
+        )
+        conn._select = mock.Mock(wraps=FakeSocketHTTPConnection.fake_select)
+        with mock.patch.object(client, 'ssl',
+                               mock.Mock(SSLSocket=FakeSSLSocket)):
+            conn.request('PUT', '/', headers={'Expect': '100-continue'},
+                         body=b'Body content', continue_timeout=0.25)
+        conn._select.assert_called_once_with([conn.sock], [], [], 0.25)
+        self.assertEqual(conn.getresponse().code, 200)
+        self.assertIn(b'Body content', conn.sock.data)
+
+    def test_pending_response_kept_on_invalid_putrequest(self):
+        # A real socket is needed: FakeSocket.makefile() returns the whole
+        # response again, which would hide a lost early response.
+        def server_thread(sock):
+            conn, _ = sock.accept()
+            with conn:
+                conn.recv(4096)
+                conn.sendall(
+                    b'HTTP/1.1 417 Expectation Failed\r\n'
+                    b'Content-Length: 4\r\n'
+                    b'\r\n'
+                    b'nope'
+                )
+                # Keep the connection open until the client is done.
+                conn.recv(4096)
+
+        with socket.socket() as sock:
+            sock.bind(('localhost', 0))
+            sock.listen(1)
+            t = threading.Thread(target=server_thread, args=(sock,))
+            t.start()
+            conn = client.HTTPConnection('localhost', sock.getsockname()[1],
+                                         timeout=support.SHORT_TIMEOUT)
+            try:
+                conn.request('PUT', '/',
+                             headers={'Expect': '100-continue'},
+                             body=b'Body content')
+                with self.assertRaises(client.CannotSendRequest):
+                    conn.putrequest('GET', '/')
+                with conn.getresponse() as resp:
+                    self.assertEqual(resp.status, 417)
+                    self.assertEqual(resp.read(), b'nope')
+            finally:
+                conn.close()
+                t.join()
+
+    def test_body_sent_on_timeout(self):
+        def client_thread(port):
+            conn = client.HTTPConnection('localhost', port)
+            conn.request('PUT', '/',
+                         headers={'Expect': '100-continue'},
+                         body=b'Body content', continue_timeout=0.75)
+            resp = conn.getresponse()
+            self.assertEqual(resp.code, 200)
+            resp.close()
+            conn.close()
+
+        with threading_helper.catch_threading_exception() as cm:
+            with socket.socket() as sock:
+                sock.bind(('localhost', 0))
+                sock.listen(1)
+                t = threading.Thread(target=client_thread,
+                                     args=(sock.getsockname()[1],))
+                t.start()
+                conn, _ = sock.accept()
+                req_data = conn.recv(4096)
+                self.assertTrue(req_data.startswith(b'PUT / HTTP/1.1\r\n'))
+                self.assertIn(b'Expect: 100-continue\r\n', req_data)
+                self.assertIn(b'Content-Length: 12\r\n', req_data)
+                # Client should not send body data yet
+                self.assertNotIn(b'Body content', req_data)
+
+                # Server does not respond to the continue request with 100 
Continue
+                # so the client will time out and send the body data
+                # Wait for 0.5 seconds to see if the client sends the body data
+                rr, _, _ = select.select([conn], [], [], 0.5)
+                self.assertEqual(rr, [])
+                # Client should time out and send body data in another ~0.25s
+                rr, _, _ = select.select([conn], [], [], 0.5)
+                self.assertEqual(rr, [conn])
+                body = conn.recv(4096)
+                self.assertEqual(body, b'Body content')
+                conn.sendall(
+                    b'HTTP/1.1 200 OK\r\n'
+                    b'Content-Length: 0\r\n'
+                    b'\r\n'
+                )
+                conn.close()
+                sock.close()
+                t.join()
+            if cm.exc_value is not None:
+                raise cm.exc_value
+
+    def test_manual_getresponse(self):
+        def client_thread(port):
+            conn = client.HTTPConnection('localhost', port)
+            conn.putrequest("PUT", "/file", continue_timeout=0.1)
+            conn.putheader('Expect', '100-Continue')
+            conn.putheader('Content-Length', '42')
+            conn.endheaders()
+            with conn.getresponse(support_continue=True) as resp:
+                self.assertEqual(resp.status, 100)
+            conn.send(b'Go away or I shall taunt you a second time')
+            with conn.getresponse() as resp:
+                self.assertEqual(resp.status, 200)
+            conn.close()
+
+        with threading_helper.catch_threading_exception() as cm:
+            with socket.socket() as sock:
+                sock.bind(('localhost', 0))
+                sock.listen(1)
+                t = threading.Thread(target=client_thread,
+                                     args=(sock.getsockname()[1],))
+                t.start()
+                conn, _ = sock.accept()
+                req_data = conn.recv(4096)
+                self.assertTrue(req_data.startswith(b'PUT /file HTTP/1.1\r\n'))
+                self.assertIn(b'Expect: 100-Continue\r\n', req_data)
+                self.assertIn(b'Content-Length: 42\r\n', req_data)
+                self.assertNotIn(b'I shall taunt you', req_data)
+                # Client is not expected to send body data until we respond,
+                # regardless of continue_timeout
+                rr, _, _ = select.select([conn], [], [], 1.0)
+                self.assertEqual(rr, [])
+                conn.sendall(b'HTTP/1.1 100 Continue\r\n\r\n')
+                rr, _, _ = select.select([conn], [], [], 0.5)
+                self.assertEqual(rr, [conn])
+                b = conn.recv(42)
+                self.assertEqual(
+                    b, b'Go away or I shall taunt you a second time')
+                conn.sendall(
+                    b'HTTP/1.1 200 OK\r\n'
+                    b'Content-Length: 0\r\n'
+                    b'\r\n'
+                )
+                conn.close()
+                sock.close()
+                t.join()
+            if cm.exc_value is not None:
+                raise cm.exc_value
+
+
+
 class HTTPResponseTest(TestCase):
 
     def setUp(self):
diff --git a/Misc/ACKS b/Misc/ACKS
index 4178ae3108128a..c3ecfc1e315a59 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -117,6 +117,7 @@ Cesar Eduardo Barros
 Des Barry
 Emanuel Barry
 Ulf Bartelt
+Tim Bartlett
 Campbell Barton
 Don Bashford
 Pior Bastida
@@ -1270,6 +1271,7 @@ Rihaan Meher
 Bill van Melle
 Lucas Prado Melo
 Ezio Melotti
+Ashwin Menon
 Doug Mennella
 Dimitri Merejkowsky
 Brian Merrell
diff --git 
a/Misc/NEWS.d/next/Library/2026-09-27-13-04-02.gh-issue-42550.sqYlvB.rst 
b/Misc/NEWS.d/next/Library/2026-09-27-13-04-02.gh-issue-42550.sqYlvB.rst
new file mode 100644
index 00000000000000..af8fe2630ba440
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-27-13-04-02.gh-issue-42550.sqYlvB.rst
@@ -0,0 +1,3 @@
+:class:`http.client.HTTPConnection` now waits for a ``100 Continue``
+response before sending body content if the ``Expect: 100-Continue`` header
+is set.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to