如何同时在两个类中使用urllib2

How to use urllib2 in two classes at the same time

我正在编写一个同步脚本。 我写了两个 classes 来完成它

class jira:
    def __init__(self, site, username, password):
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener()
        opener.add_handler(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)
        self.topurl = site
        loginUrl = deepcopy(self.topurl)
        loginUrl += '/rest/auth/1/session'
        user = {"username": username, "password": password}
        req = urllib2.Request(loginUrl)
        req.add_header("Content-Type", "application/json")
        req.add_data(json.dumps(user))
        try:
            res = urllib2.urlopen(req)
        except urllib2.HTTPError as err:
            print str(err)
            sys.exit(2)

class clearquest:
    def __init__(self, site, username, password):
        pwdmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        pwdmgr.add_password(None, site, username, password)
        handler = urllib2.HTTPBasicAuthHandler(pwdmgr)
        opener = urllib2.build_opener(handler)
        try:
            opener.open(site)
        except urllib2.HTTPError as err:
            print str(err)
            sys.exit(2)
        urllib2.install_opener(opener)

首先我启动了class clearquest,然后启动了jira

cq = clearquest(site, username, passowrd)
jr = jira(site, username, password)

然后我想用它们做点什么,但是我用cq的时候,提示"Unauthorized"

我知道肯定是jira的opener覆盖了clearquest的opener,但是怎么避免呢?

我已经解决了

class jira:
def __init__(self, site, username, password):
    cj = cookielib.CookieJar()
    self.opener = urllib2.build_opener()
    self.opener.add_handler(urllib2.HTTPCookieProcessor(cj))
    self.topurl = site
    loginUrl = deepcopy(self.topurl)
    loginUrl += '/rest/auth/1/session'
    user = {"username": username, "password": password}
    req = urllib2.Request(loginUrl)
    req.add_header("Content-Type", "application/json")
    req.add_data(json.dumps(user))
    try:
        res = self.opener.open(req)
    except urllib2.HTTPError as err:
        print str(err)
        sys.exit(2)

只是不使用urllib2.install_opener(opener),它将安装当前的opener并覆盖预安装,并使用self.opener.open()而不是urllib.urlopen(),它将使用class 的开启请求