Skip to content

fix: preserve custom CookiePolicy in Session.prepare_request#7123

Closed
shindonghwi wants to merge 1 commit intopsf:mainfrom
shindonghwi:fix/cookie-policy-persistence-7122
Closed

fix: preserve custom CookiePolicy in Session.prepare_request#7123
shindonghwi wants to merge 1 commit intopsf:mainfrom
shindonghwi:fix/cookie-policy-persistence-7122

Conversation

@shindonghwi
Copy link
Copy Markdown

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
@nateprewitt
Copy link
Copy Markdown
Member

Thanks for the PR, @shindonghwi. I think we'll move #4042 onto main if we decide to move forward with this.

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

2 participants