Skip to content

urllib reads the body of a redirect before following it #163110

Backlog

Description

@Dashtid

Bug report

urllib follows redirects by first reading the redirect's whole body and throwing it away. But it never reuses the connection so there's nothing to clear out which makes it kind of pointless.

For example a body that is cut short makes redirection fail even though the new address was fine.

My feed reader caps how much it downloads, but this read happens inside urllib before my cap applies, so I had to replace the handler. Python fixed the same thing in its URL opener in 2011 (bpo-8035).

Fix and test ready.

The read:

# Don't close the fp until we are sure that we won't use it
# with HTTPError.
fp.read()
fp.close()

Repro
import http.server
import threading
import urllib.request


class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/old":
            self.send_response(302)
            self.send_header("Location", "/new")
            self.send_header("Content-Length", "100")
            self.end_headers()
            self.wfile.write(b"0123456789")  # 10 of the 100 bytes announced
        else:
            self.send_response(200)
            self.send_header("Content-Length", "3")
            self.end_headers()
            self.wfile.write(b"new")

    def log_message(self, *args):
        pass


server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
print(urllib.request.urlopen(f"http://127.0.0.1:{server.server_port}/old").read())

On 3.14.10:

  File "C:\Python314\Lib\urllib\request.py", line 715, in http_error_302
    fp.read()
    ~~~~~~~^^
  File "C:\Python314\Lib\http\client.py", line 510, in read
    s = self._safe_read(self.length)
  File "C:\Python314\Lib\http\client.py", line 671, in _safe_read
    raise IncompleteRead(data, amt - len(data))
http.client.IncompleteRead: IncompleteRead(10 bytes read, 90 more expected)

With the fp.read() line removed it prints b'new'.

CPython versions tested on:

3.14, CPython main branch

Operating systems tested on:

Windows

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    on Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions