Fix AttributeError in Session.prepare_request() when Request.method is None
Summary
This PR fixes a bug where Session.prepare_request() would raise an AttributeError when called with a Request object that has method=None.
Problem
When creating a Request object without specifying a method (e.g., Request(url="https://example.com/")), the method attribute defaults to None. Subsequently calling Session.prepare_request() with this request would crash because the code attempted to call .upper() on None:
# Before fix
p.prepare(
method=request.method.upper(), # AttributeError: 'NoneType' object has no attribute 'upper'
...
)
Solution
Changed the code to default to "GET" when the method is None, matching standard HTTP behavior:
# After fix
p.prepare(
method=(request.method or "GET").upper(),
...
)
Changes
-
src/requests/sessions.py: Added fallback to
"GET"whenrequest.methodisNone -
tests/test_requests.py: Added comprehensive test case
test_prepare_request_with_none_method()to verify the fix and prevent regression
Testing
The new test case verifies that:
- A
Requestobject can be created withmethod=None -
Session.prepare_request()successfully prepares the request without crashing - The prepared request defaults to the
"GET"method - The URL is properly preserved
Impact
This is a bug fix that improves robustness and prevents unexpected crashes when using the library. The behavior aligns with HTTP standards where GET is the default method.
I should add that this issue was found because of I think (I'm not 100% sure because everything was also typed according to mypy rules in the commit) pylint in https://github.com/psf/requests/pull/7054, if it was pylint that found this issue and it is a legitimate issue then it makes a strong case for the project to start using it imo.