pythonpython-requestscookielibcookiejar

Cookie policy getting ignored?


I'm trying to use requests.Session to make some requests and I'd like cookies to not be set. Looking at this question, it appears I can create a cookie policy, and create a cookie jar given that policy to ignore cookies. However, for my requests, it would seem that cookies are still be set:

from http import cookiejar

class BlockAll(cookiejar.CookiePolicy):
        """ Blocks all cookies for a given request.
        """
        return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False
        netscape = True
        rfc2965 = hide_cookie2 = False


def get_cookie_jar():
    cookies = cookiejar.CookieJar(policy=BlockAll())
    return cookies

session = requests.Session()
response = session.request(
   method='post',
   url='some_url.com',
   cookies=get_cookie_jar(),
   ....
)

print(response.cookies)
<RequestsCookieJar[Cookie(version=0, name='JSESSIONID', value='1234', port=None, port_specified=False, domain='some_url.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>

Is this the correct way to set the policy for this type of request? Any help / links to relevant documentation would be greatly appreciated.


Solution

  • The cookies argument to request(...) lets you specify outgoing cookies on the request. It is not consulted for incoming cookies on the response.

    You need to set the policy on the session:

    session = requests.Session()
    session.cookies.set_policy(BlockAll())
    

    Demo:

    >>> session = requests.Session()
    >>> response = session.request('GET', 'http://httpbin.org/cookies/set?foo=bar')
    >>> session.cookies  # no policy, so cookie got set
    <RequestsCookieJar[Cookie(version=0, name='foo', value='bar', port=None, port_specified=False, domain='httpbin.org', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>
    >>> session.cookies.clear()  # clean slate, no cookies
    >>> session.cookies
    <RequestsCookieJar[]>
    >>> session.cookies.set_policy(BlockAll())
    >>> response = session.request('GET', 'http://httpbin.org/cookies/set?foo=bar')
    >>> session.cookies  # with policy, cookies still empty
    <RequestsCookieJar[]>