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
18 changes: 14 additions & 4 deletions httpx/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -985,13 +985,18 @@ def _send_handling_redirects(
if not response.has_redirect_location:
return response

request = self._build_redirect_request(request, response)
try:
next_request = self._build_redirect_request(request, response)
except (InvalidURL, RemoteProtocolError):
return response

history = history + [response]

if follow_redirects:
response.read()
request = next_request
else:
response.next_request = request
response.next_request = next_request
return response

except BaseException as exc:
Expand Down Expand Up @@ -1701,13 +1706,18 @@ async def _send_handling_redirects(
if not response.has_redirect_location:
return response

request = self._build_redirect_request(request, response)
try:
next_request = self._build_redirect_request(request, response)
except (InvalidURL, RemoteProtocolError):
return response

history = history + [response]

if follow_redirects:
await response.aread()
request = next_request
else:
response.next_request = request
response.next_request = next_request
return response

except BaseException as exc:
Expand Down
18 changes: 12 additions & 6 deletions tests/client/test_redirects.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,11 @@ def test_malformed_redirect():

def test_invalid_redirect():
client = httpx.Client(transport=httpx.MockTransport(redirects))
with pytest.raises(httpx.RemoteProtocolError):
client.get("http://example.org/invalid_redirect", follow_redirects=True)
response = client.get("http://example.org/invalid_redirect", follow_redirects=True)
assert response.status_code == httpx.codes.SEE_OTHER
assert response.url == "http://example.org/invalid_redirect"
assert not response.history
assert response.next_request is None


def test_no_scheme_redirect():
Expand Down Expand Up @@ -441,7 +444,10 @@ def test_redirect_custom_scheme():
@pytest.mark.anyio
async def test_async_invalid_redirect():
async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:
with pytest.raises(httpx.RemoteProtocolError):
await client.get(
"http://example.org/invalid_redirect", follow_redirects=True
)
response = await client.get(
"http://example.org/invalid_redirect", follow_redirects=True
)
assert response.status_code == httpx.codes.SEE_OTHER
assert response.url == "http://example.org/invalid_redirect"
assert not response.history
assert response.next_request is None