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

时间:2015-01-05 10:59:08

标签: python urllib2

我正在写一个同步脚本。 我写了两个课来做它

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)

首先我参加了课程clearquest然后inited jira

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

然后我想用它们来做某事,但当我使用cq时,它会指出"未经授权"

我知道必须是jira的揭幕战覆盖了clearquest的开场白,但我该如何避免呢?

1 个答案:

答案 0 :(得分:0)

我已经解决了它

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(),它将使用类的opener来打开请求< / p>