urllib2 and Set-Cookie with "302 Moved temporarily"

Fredrik Lundh fredrik at pythonware.com
Mon Dec 13 17:48:49 CET 2004


"Eino Mäkitalo" <eino at iki.fi> wrote:

> It seems that urrlib2 default redirection does not allow me to handle
> Cookies. Service I'm trying seems to use IP switcher and session id's with cookies. After 
> successful login it changes session id (PD-H_SESSION-ID) in 302 Moved temporarily.

and adds a new cookie.

> Urllib2 is so clever that it handles redirection but with wrong cookies.

with the old cookies, that is.  that's stupid.

here's an ugly hack for the old urllib that looks for set-cookie headers in
redirects, and adds corresponding cookie headers to the new request:

import urllib

class my_url_opener(urllib.FancyURLopener):

    def http_error_302(self, *args):
        headers = args[4]
        # print headers # <-- uncomment to see the headers
        cookie = headers.get("set-cookie")
        if cookie:
            # this is ugly
            self.addheaders.append(("Cookie", cookie.split(";")[0]))
        return urllib.FancyURLopener.http_error_302(self, *args)

myurlopen = my_url_opener().open

myurlopen("http://www.google.com")

</F> 






More information about the Python-list mailing list