how to remove specified cookie in cookie jar?

John J. Lee jjl at pobox.com
Sun Apr 1 11:35:21 EDT 2007


"ken" <ken.carlino at gmail.com> writes:

> How to remove specified cookie (via a given name) in cookie jar?
> 
> I have the following code, but how can I remove a specified cookie in
> the cookie jar?
>  cj = cookielib.LWPCookieJar()
> 
>  if cj is not None:
>      if os.path.isfile(COOKIEFILE):
>             print 'Loading Cookie--------------'
>             cj.load(COOKIEFILE)

cj.clear('example.com', '/', 'cookiename')


Note that the domain arg must match the cookie domain exactly (and the
domain might, for example, start with a dot).  You may want to iterate
over the Cookie objects in the CookieJar to find the one(s) you want
to remove, but it's not supported to remove them at the same time as
iterating, so (UNTESTED):

remove = []
for cookie in cj:
    if is_to_be_removed(cookie):
        remove.append(cookie)
for cookie in remove:
    cj.clear(cookie.domain, cookie.path, cookie.name)


http://docs.python.org/lib/cookie-jar-objects.html

"""
clear(  	[domain[, path[, name]]])
    Clear some cookies.

    If invoked without arguments, clear all cookies. If given a single
    argument, only cookies belonging to that domain will be
    removed. If given two arguments, cookies belonging to the
    specified domain and URL path are removed. If given three
    arguments, then the cookie with the specified domain, path and
    name is removed.

    Raises KeyError if no matching cookie exists. 
"""


John



More information about the Python-list mailing list