Can a cookiejar object be pickled?

房东的猫 提交于 2019-12-23 13:24:10

问题


I tried pickling a CookieJar object like this:

import cookielib
import pickle

dumpFile = open('cookie.dump','w')
cj = cookielib.CookieJar()
pickle.dump(cj, dumpFile)

It raised the following exception:

raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle lock objects

Can a CookieJar be pickled?


回答1:


The answer to the question as asked is "no": the jar itself is not pickle-able.

However, the cookies contained in the jar, are:

pickle.dump([c for c in cj], dumpFile)

will do the trick, for instance. (You can then load the result and insert the list of cookies into a new jar. You will probably want to check them for expiration and such first though. Depending on when you're doing the pickling you might even want to check before dumping.)




回答2:


The answer is "yes", but only if you use a better serializer than pickle.

>>> import cookielib
>>> import dill
>>> 
>>> cj = cookielib.CookieJar()
>>> _cj = dill.dumps(cj)
>>> cj_ = dill.loads(_cj)
>>> cj_
<CookieJar[]>



回答3:


Might you be better served by using an implementation of FileCookieJar like MozillaCookieJar or LWPCookieJar, and their save() methods?



来源:https://stackoverflow.com/questions/18169748/can-a-cookiejar-object-be-pickled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!