Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Lib/test/test_urllib2.py
Original file line number Diff line number Diff line change
Expand Up @@ -1465,6 +1465,33 @@ def redirect(h, req, url=to_url):
urllib.request.HTTPRedirectHandler.max_redirections)
err.close()

def test_redirect_does_not_read_body(self):
# The body of a redirect response is closed without being read.
from_url = "http://example.com/a.html"
to_url = "http://example.com/b.html"

class UnreadFile(MockFile):
read_called = closed = False

def read(self, count=None):
self.read_called = True

def close(self):
self.closed = True

for code in 301, 302, 303, 307, 308:
with self.subTest(code=code):
h = urllib.request.HTTPRedirectHandler()
o = h.parent = MockOpener()
req = Request(from_url)
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
fp = UnreadFile()
getattr(h, "http_error_%s" % code)(
req, fp, code, "Blah", MockHeaders({"location": to_url}))
self.assertFalse(fp.read_called)
self.assertTrue(fp.closed)
self.assertEqual(o.req.get_full_url(), to_url)

def test_invalid_redirect(self):
from_url = "http://example.com/a.html"
valid_schemes = ['http','https','ftp']
Expand Down
1 change: 0 additions & 1 deletion Lib/urllib/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,6 @@ def http_error_302(self, req, fp, code, msg, headers):

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we know why we are reading it? What was the reason to read it in the first place?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not that I could find. It was already in urllib2's first commit in 2000, and no commit message since explains it; the comment above it was added in 2001 and is about when fp gets closed. The old urllib had the same read from 1995 with no stated reason either (gh-54786), and it was removed there for bpo-8035. Reading the rest of a response is normally done so the connection can be reused, but do_open() sends Connection: close and closes the socket.

fp.close()

return self.parent.open(new, timeout=req.timeout)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:class:`urllib.request.HTTPRedirectHandler` no longer reads the body of a
redirect response before following the redirect.
Loading