n00b with urllib2: How to make it handle cookie automatically?

7stud bbxx789_05ss at yahoo.com
Fri Feb 22 16:57:04 EST 2008


On Feb 21, 11:50 pm, est <electronix... at gmail.com> wrote:
> Hi all,
>
> I need urllib2 do perform series of HTTP requests with cookie from
> PREVIOUS request(like our browsers usually do ).
>

Cookies from a previous request made in the currently running
program?  Or cookies from requests that were made when you previously
ran the program?

>
> from cookielib import CookieJar
> class SmartRequest():
>     cj=CookieJar()
>     def __init__(self, strUrl, strContent=None):
>         self.Request    =   urllib2.Request(strUrl, strContent)
>         self.cj.add_cookie_header(self.Request)
>         self.Response   =   urllib2.urlopen(Request)
>         self.cj.extract_cookies(self.Response, self.Request)
>     def url
>     def read(self, intCount):
>         return self.Response.read(intCount)
>     def headers(self, strHeaderName):
>         return self.Response.headers[strHeaderName]
>
> The code does not work because each time SmartRequest is initiated,
> object 'cj' is cleared. How to avoid that?
> The only stupid solution I figured out is use a global CookieJar
> object. Is there anyway that could handle all this INSIDE the class?
>

Examine this code and its output:

class SmartRequest(object):
    def __init__(self, id):
        if not getattr(SmartRequest, 'cj', None):
            SmartRequest.cj = "I'm a cookie jar. Created by request:
%s" % id


r1 = SmartRequest(1)
r2 = SmartRequest(2)

print r1.cj
print r2.cj

--output:--
I'm a cookie jar. Created by request: 1
I'm a cookie jar. Created by request: 1



More information about the Python-list mailing list