pythonurllib2cookiejarcookielib

Cookiejar use in an opener


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?


Solution

  • 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.