2

I have the following code at the moment:

tw_jar = cookielib.CookieJar()
tw_jar.set_cookie(c1)
tw_jar.set_cookie(c2)

o = urllib2.build_opener( urllib2.HTTPCookieProcessor(tw_jar) )
urllib2.install_opener( o )

Now I later in my code I don't want to use any of the cookies (Also new cookies created meanwhile).

Can I do a simple tw_jar.clear() or do I need to build and install the opener again to get rid of all cookies used in the requests?

jcollado
  • 39,419
  • 8
  • 102
  • 133
user774166
  • 45
  • 3
  • Do you need to clear old cookies, but still continue processing new ones or don't use any cookie at all? – jcollado Dec 21 '11 at 19:41

2 Answers2

2

This is how HTTPCookieProcessor is defined in my Python installation:

class HTTPCookieProcessor(BaseHandler):
  def __init__(self, cookiejar=None):
    import cookielib
    if cookiejar is None:
        cookiejar = cookielib.CookieJar()
    self.cookiejar = cookiejar

  def http_request(self, request):
    self.cookiejar.add_cookie_header(request)
    return request

  def http_response(self, request, response):
    self.cookiejar.extract_cookies(response, request)
    return response

  https_request = http_request
  https_response = http_response

As only a reference is saved, you can just manipulate the original tw_jar instance and it will affect all future requests.

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
0

If you don't want any cookies, I'd recommend to create a new opener. However, if for some reason you want to keep the old one, removing the cookie processor from the list of handlers should work:

o.handlers = [h for h in o.handlers
              if not isinstance(h, urllib2.HTTPCookieProcessor)]
jcollado
  • 39,419
  • 8
  • 102
  • 133