Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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)]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top