Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Easier way to disable cookie persistence #1417

Closed
esaurito opened this issue Jun 11, 2013 · 2 comments
Closed

Easier way to disable cookie persistence #1417

esaurito opened this issue Jun 11, 2013 · 2 comments

Comments

@esaurito
Copy link

I was looking for a way to temporary disable cookie persistence.
When I use requests to access an URL cookies are automatically sent back to the server (in the following example the requested URL set some cookie values and then redirect to another URL that display the stored cookie)

>>> import requests
>>> response = requests.get("http://httpbin.org/cookies/set?k1=v1&k2=v2")
>>> response.content
'{\n  "cookies": {\n    "k2": "v2",\n    "k1": "v1"\n  }\n}'

Is it possible to temporary disable cookie handling in the same way you set Chrome or Firefox to not accept cookies?

I made this question on SO and it seems that the only way to go is patching the requests.cookies.RequestsCookieJar.update. I think that should be an easier way to do this in requests, Maybe passing parameter to the get method?

@Lukasa
Copy link
Member

Lukasa commented Jun 11, 2013

Hi @esaurito, thanks for raising this issue!

By design Requests' primary API supports the 90% use-case, which involves persisting cookies. We are very unlikely to add a parameter to the main methods to allow you not to persist cookies.

If you absolutely don't want to, my recommendation is that you use a session along with a subclass of the RequestsCookieJar. I haven't tried the following, but it ought to work:

import requests
from requests.cookies import RequestsCookieJar

class BlackHoleCookieJar(RequestsCookieJar):
    """
    This class's attitude to cookies can be described in three words: nom nom nom.
    """
    def set(self, name, value, **kwargs):
        pass

    def update(self, other):
        pass

s = requests.Session()
s.cookies = BlackHoleCookieJar()

Subsequent requests through that session should throw cookies away. Bear in mind that the BlackHoleCookieJar above is for example purposes only: in real code there are a few other methods you'd want to override, like .copy().

Is this helpful?

@esaurito
Copy link
Author

Thank you very much for the explanation and the sample code. At first I thought that cookie persistence were available only for sessions. I'll go with the BlackHoleCookieJar.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 9, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants