Fix: Preserve custom CookiePolicy in Session.prepare_request #7131
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 fixes an issue where custom CookiePolicy objects set on a session’s cookie jar were being lost during request preparation.
The Problem
When requests.Session.prepare_request() merged cookies, it created a new RequestsCookieJar without copying over the policy from the session jar. As a result, custom policies (like allowing secure cookies on localhost) worked when storing cookies, but not when preparing requests to send them.
The Fix
The merge logic in prepare_request() now preserves the existing policy by applying the session jar’s policy to the new jar before merging. This ensures policy decisions are still consulted during request preparation.
Impact
This resolves long-standing issue #7122 and restores the ability to rely on custom cookie policy behavior without breaking existing functionality. The change is contained, minimal, and only affects scenarios where a custom policy is explicitly set.