如何在类中存储可在函数之间使用的cookie jar?

2 投票
2 回答
1830 浏览
提问于 2025-04-16 16:37

我想听听你们的建议,关于如何有效地存储 cookies,以便在一个类里面被其他函数使用。我的当前代码是这样的:

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

虽然上面的例子可以运行,但如果我不想用 cookies 发请求,就必须自己构建一个 Request(),我相信一定有更好、更优雅的方法来做到这一点。

谢谢大家。

2 个回答

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

我把原来的内容注释掉了,这样可以突出我所做的修改。

3

首先,正如jathanism提到的,你实际上并没有安装cookie jar。

import cookielib
...

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) 

然后,urllib2.install_opener(opener)会全局安装这个opener,这个其实你并不需要。把urllib2.install_opener(opener)这一行去掉。

对于不需要cookie的请求,可以这样做:

你不需要自己构建Request对象,只需直接用url和参数调用urlopen就可以了:

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

对于需要cookie的请求,使用opener对象:

self.opener.urlopen(url, data)

撰写回答