Skip to content

Conversation

@shindonghwi
Copy link

Summary

When using a custom CookiePolicy on a session's CookieJar, the policy was being discarded when Session.prepare_request() was called. This happened because the code was creating a new RequestsCookieJar() with the default policy instead of copying the session's jar with its policy preserved.

This fix uses the existing _copy_cookie_jar() function to properly preserve the CookiePolicy when merging cookies.

Related Issues

Changes

  • Import _copy_cookie_jar in sessions.py
  • Use _copy_cookie_jar(self.cookies) instead of merge_cookies(RequestsCookieJar(), self.cookies) in prepare_request()
  • Added test case test_cookie_policy_preserved_on_prepare_request

Test Plan

from requests.cookies import RequestsCookieJar
from http.cookiejar import DefaultCookiePolicy
import requests

class BlockAllCookies(DefaultCookiePolicy):
    def set_ok(self, cookie, request):
        return False

s = requests.Session()
jar = RequestsCookieJar(policy=BlockAllCookies())
s.cookies = jar

req = requests.Request('GET', 'https://example.com/')
prepared = s.prepare_request(req)

# Before fix: DefaultCookiePolicy
# After fix: BlockAllCookies
print(type(prepared._cookies.get_policy()))

Use _copy_cookie_jar to preserve the session's CookiePolicy when
preparing requests, instead of creating a new RequestsCookieJar
with the default policy.

Fixes psf#7122, psf#3416
@shindonghwi shindonghwi force-pushed the fix/cookie-policy-persistence-7122 branch from b6bf410 to 12502bc Compare December 18, 2025 13:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unable to override cookie policy in Session.prepare_request

1 participant