requests icon indicating copy to clipboard operation
requests copied to clipboard

Fix AttributeError in Session.prepare_request() when Request.method is None

Open tboy1337 opened this issue 3 months ago • 1 comments

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" when request.method is None
  • 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:

  1. A Request object can be created with method=None
  2. Session.prepare_request() successfully prepares the request without crashing
  3. The prepared request defaults to the "GET" method
  4. 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.

tboy1337 avatar Oct 21 '25 13:10 tboy1337

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.

tboy1337 avatar Oct 22 '25 12:10 tboy1337