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

est electronixtar at gmail.com
Sun Feb 24 06:01:43 EST 2008


On Feb 23, 5:57 am, 7stud <bbxx789_0... at yahoo.com> wrote:
> 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:

the getattr method is exactly what I am looking for, thanks!


On Feb 23, 2:05 pm, 7stud <bbxx789_0... at yahoo.com> wrote:
> On Feb 21, 11:50 pm, est <electronix... at gmail.com> wrote:
>
>
>
> > class SmartRequest():
>
> You should always define a class like this:
>
> class SmartRequest(object):
>
> unless you know of a specific reason not to.

Thanks for the advice!



More information about the Python-list mailing list