Python urllib2多进程共享cookies

如果想多个进程共享同一个cookies,不用每个进程都重新登录,可以就cookies保存到一个文件,然后多个进程直接共享一个锁来实现

1.一个进程登录完成后,把cookies保存到一个文件里面

self.cookies.save(self.cookies_file,ignore_discard=True, ignore_expires=True)

2.获取一个实例,或者实例化后,从cookies文件里面加载cookies

def install_cookies_opener(self):
    if not os.path.exists(self.cookies_file):
        with open(self.cookies_file,'w') as f:
            pass
    self.cookies = cookielib.LWPCookieJar()
    try:
        self.cookies.load(self.cookies_file,ignore_discard=True, ignore_expires=True)
    except:
        print traceback.format_exc()
    handlers = [
        urllib2.HTTPHandler(),
        urllib2.HTTPSHandler(),
        urllib2.HTTPCookieProcessor(self.cookies)
    ]
    opnner = urllib2.build_opener(*handlers)
    urllib2.install_opener(opnner)

你可能感兴趣的:(Python urllib2多进程共享cookies)