Update Response.raise_for_status() to respect follow_redirects parameter
#3631
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR enhances the
Response.raise_for_status()method to detect when redirect responses (3xx status codes) automatically should not raise exceptions. When a request is made withfollow_redirects=False, HTTPX setsresponse.next_requestfor redirect responses, andraise_for_status()now intelligently detects this and treats redirects as successful responses instead of raisingHTTPStatusError.This change addresses the inconsistency where developers had to manually check
response.next_requestor implement custom logic to handle redirects whenfollow_redirects=Falsewas set on the request.Current Behaviour
raise_for_status()always raisesHTTPStatusErrorfor 3xx redirect responsesresponse.next_requestmanuallyExpected Behaviour
raise_for_status()automatically detects when redirects shouldn't raise exceptionsfollow_redirects=Falseis set on the request, redirect responses are treated as successfulChanges Made
-
httpx/_models.py: Modifiedraise_for_status()method to check fornext_requestpresence and return early for redirects whenfollow_redirects=Falsetests/models/test_responses.py: Added test case to verify that redirect responses don't raise exceptions whenfollow_redirects=Falsedocs/quickstart.md: Updated documentation to explain the new redirect handling behaviour with clear examplesChecklist
[x] I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
[x] I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
[x] I've updated the documentation accordingly.