如何存储Cookie罐以在类内部的函数之间使用? [英] How to store cookie jar to be used between functions inside class?

查看:115
本文介绍了如何存储Cookie罐以在类内部的函数之间使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想听听您关于如何有效存储cookie的建议,这些建议将在类中由其他函数使用.我当前的代码如下:

I'd like to hear your suggestions on how to effectively store cookies, that are to be used inside a class by other functions. My current code looks like this:

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

尽管上面的示例可行,但是如果我不想使用cookie发出请求,则必须构建自定义Request(),并且我确信必须有更好,更优雅的方法来执行此操作.

Although above example works, I must build custom Request() if I do NOT want to make request with cookies and I am sure there must be better and more elegant way to do this.

谢谢.

推荐答案

首先,正如詹森(Jathanism)所注意到的,您实际上并没有安装Cookie罐.

First, as jathanism noticed, you are not actually installing the cookie jar.

import cookielib
...

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

然后,urllib2.install_opener(opener)将全局安装该打开器(!),您无需这样做.删除urllib2.install_opener(opener).

Then, urllib2.install_opener(opener) will install the opener globally(!), which you do not need to do. Remove urllib2.install_opener(opener).

对于非Cookie请求,请执行以下操作:

For non-cookie requests do this:

您不需要构建Request对象,只需使用url和params调用urlopen:

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)

对于Cookie请求,请使用打开器对象:

For cookie requests, use the opener object:

self.opener.urlopen(url, data)

这篇关于如何存储Cookie罐以在类内部的函数之间使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆