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

荒凉一梦 提交于 2019-12-06 05:03:30

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)
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!