2

I'd like to hear your suggestions on how to effectively store cookies, that are to be used inside a class by other functions. My current code looks like this:

class SomeClass:
    def __init__(self, username, password):
        self.logged_in      = False
        self.username       = username
        self.password       = password
        opener              = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        urllib2.install_opener(opener)

    def _login(self, username, password):
        if not self.logged_in:
            params = urllib.urlencode({'username': username, 'password': password})
            conn = urllib2.Request('http://somedomain.com/login', params)
            urllib2.urlopen(conn)
            self.logged_in = True

    def _checkLogin(self):
        if not self.logged_in:
            self._login(self.username, self.password)

    def doSomeStuffThatRequireCookies(self):
        self._checkLogin()
        data = urllib2.urlopen(conn).read()
        return data

Although above example works, I must build custom Request() if I do NOT want to make request with cookies and I am sure there must be better and more elegant way to do this.

Thank you.

Gargauth
  • 2,115
  • 6
  • 24
  • 28

2 Answers2

3

First, as jathanism noticed, you are not actually installing the cookie jar.

import cookielib
...

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) 

Then, urllib2.install_opener(opener) will install the opener globally(!), which you do not need to do. Remove urllib2.install_opener(opener).

For non-cookie requests do this:

You don't need to build the Request object, you can just call urlopen with url and params:

params = urllib.urlencode({'username': username, 'password': password})
urllib2.urlopen('http://somedomain.com/login', params)

For cookie requests, use the opener object:

self.opener.urlopen(url, data)
theduke
  • 2,702
  • 4
  • 26
  • 28
  • Thank you very much. But I think you forgot to add code snippet under "For non-cookie requests do this" part of your answer. – Gargauth Apr 28 '11 at 23:25
  • This answer was super helpful to me, except for one small issue. `OpenerDirector` objects do not have a `urlopen` function; the last line of your answer should just be `self.opener.open(url, data)`. – dg99 Dec 17 '13 at 20:25
1
import cookielib

class SomeClass:
    def __init__(self, username, password):
        #self.logged_in      = False
        #self.username       = username
        #self.password       = password
        self.cookiejar      = cookielib.CookieJar()
        opener              = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar))
        #urllib2.install_opener(opener)

I commented out the stuff that was already there to highlight what I changed.

jathanism
  • 30,623
  • 9
  • 64
  • 86