将 cookielib cookie 存储在数据库中

发布于 2024-09-05 18:44:35 字数 433 浏览 16 评论 0原文

在 Python 2.6 中使用 urllib2 模块时,我使用 cookielib 模块来处理 HTTP cookie,其方式类似于此代码片段:

import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

我想将 cookie 存储在一个数据库。我不知道什么更好 - 序列化 CookieJar 对象并存储它,或者从 CookieJar 中提取 cookie 并存储它。我不知道哪个更好,也不知道如何实施它们。我还应该能够重新创建 CookieJar 对象。

有人可以帮我解决上述问题吗?

提前致谢。

I'm using the cookielib module to handle HTTP cookies when using the urllib2 module in Python 2.6 in a way similar to this snippet:

import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

I'd like to store the cookies in a database. I don't know whats better - serialize the CookieJar object and store it or extract the cookies from the CookieJar and store that. I don't know which one's better or how to implement either of them. I should be also be able to recreate the CookieJar object.

Could someone help me out with the above?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蒲公英的约定 2024-09-12 18:44:35

cookielib.Cookie,引用其文档字符串(在其

故意是一个非常简单的类。
它只包含属性。

因此,pickle(或其他序列化方法)非常适合保存和恢复每个 Cookie 实例。

对于CookieJarset_cookie设置/添加一个cookie实例,__iter__(要使用后者,只需执行for 在 jar 实例上循环)返回它所持有的所有 cookie 实例,一个接一个。

您可以使用一个子类来查看如何在数据库上制作“cookie jar”,该子类是 BSDDBCookieJarmechanize 的一部分,但我只是专门指出了 jar 源代码文件)——它不会将所有 cookie 加载到内存中,而是将它们保存在一个self._db 是一个 bsddb 实例(主要在磁盘上,类似于字典的哈希表,仅限于只有字符串作为键和值),并使用 pickle 进行序列化。

如果您同意在操作期间将每个cookie保留在内存中,那么简单地picklejar是最简单的(当然,将blob放入数据库中并将其取回)当你重新启动时) - s = cPickle.dumps(myJar, -1) 为你提供整个 jar 的大字节字符串(当然还有其中的策略,不仅仅是 cookies ),并且一旦您从数据库将 s 重新加载为 blob,theJar = cPickle.loads(s) 就会重建它。

cookielib.Cookie, to quote its docstring (in its sources),

is deliberately a very simple class.
It just holds attributes.

so pickle (or other serialization approaches) are just fine for saving and restoring each Cookie instance.

As for CookieJar, set_cookie sets/adds one cookie instance, __iter__ (to use the latter, just do a for loop on the jar instance) returns all cookie instances it holds, one after the other.

A subclass that you can use to see how to make a "cookie jar on a database" is BSDDBCookieJar (part of mechanize, but I just pointed specifically to the jar source code file) -- it doesn't load all cookies in memory, but rather keeps them in a self._db which is a bsddb instance (mostly-on-disk, dict-lookalike hash table constrained to having only strings as keys and values) and uses pickle for serialization.

If you are OK with keeping every cookie in memory during operations, simply pickleing the jar is simplest (and, of course, put the blob in the DB and get it back from there when you're restarting) -- s = cPickle.dumps(myJar, -1) gives you a big byte string for the whole jar (and policy thereof, of course, not just the cookies), and theJar = cPickle.loads(s) rebuilds it once you've reloaded s as a blob from the DB.

⒈起吃苦の倖褔 2024-09-12 18:44:35

这是我实现的一个非常简单的类,它可以根据 Alex 使用 pickle 的建议,从字符串加载 cookie 或将 cookie 转储到字符串。

from cookielib import CookieJar
try:
    import cPickle as pickle
except ImportError:
    import pickle

class StringCookieJar(CookieJar):
    def __init__(self, string=None, policy=None):
        CookieJar.__init__(self, policy)
        if string:
            self._cookies = pickle.loads(string)

    def dump(self):
        return pickle.dumps(self._cookies)

Here's a very simple class that I have implemented that can load/dump cookies from/to a string based on Alex' suggestion of using pickle.

from cookielib import CookieJar
try:
    import cPickle as pickle
except ImportError:
    import pickle

class StringCookieJar(CookieJar):
    def __init__(self, string=None, policy=None):
        CookieJar.__init__(self, policy)
        if string:
            self._cookies = pickle.loads(string)

    def dump(self):
        return pickle.dumps(self._cookies)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文