python - How to store cookie jar to be used between functions inside class? -


i'd hear suggestions on how store cookies, used inside class other functions. current code looks 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, must build custom request() if not want make request cookies , sure there must better , more elegant way this.

thank you.

first, jathanism noticed, not installing cookie jar.

import cookielib ...  opener = urllib2.build_opener(urllib2.httpcookieprocessor(cookielib.cookiejar()))  

then, urllib2.install_opener(opener) install opener globally(!), not need do. remove urllib2.install_opener(opener).

for non-cookie requests this:

you don't need build request object, can call urlopen url , params:

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

for cookie requests, use opener object:

self.opener.urlopen(url, data) 

Comments