Skip to content

Instantly share code, notes, and snippets.

@PyYoshi
Created June 4, 2012 09:56
Show Gist options
  • Select an option

  • Save PyYoshi/2867549 to your computer and use it in GitHub Desktop.

Select an option

Save PyYoshi/2867549 to your computer and use it in GitHub Desktop.
cookiejarをファイルに保存するのではなく文字列として使えるようにするアレ。 google cookie専用
# coding:utf-8
# google用cookie
# License: MIT
import cookielib
import simplejson
def cookiejar_to_jsonstring(cookiejar):
cookies = cookiejar._cookies['.google.com']['/']
cookies_list = []
for cookie in cookies.items():
cookie_obj = {
'comment':cookie[1].comment,
'comment_url':cookie[1].comment_url,
'rest':cookie[1]._rest,
'discard':cookie[1].discard,
'expires':cookie[1].expires,
'secure':cookie[1].secure,
'path':cookie[1].path,
'path_specified':cookie[1].path_specified,
'domain':cookie[1].domain,
'domain_specified':cookie[1].domain_specified,
'domain_initial_dot':cookie[1].domain_initial_dot,
'port':cookie[1].port,
'port_specified':cookie[1].port_specified,
'version':cookie[1].version,
'name':cookie[1].name,
'value':cookie[1].value,
'rfc2109':cookie[1].rfc2109,
}
cookies_list.append(cookie_obj)
return simplejson.dumps(cookies_list)
def jsonstring_to_cookiejar(cookies_jsonstring):
cj = cookielib.CookieJar()
cookies = simplejson.loads(cookies_jsonstring)
for cookie in cookies:
c = cookielib.Cookie(
version = cookie['version'],
name = cookie['name'],
value = cookie['value'],
port = cookie['port'],
port_specified = cookie['port_specified'],
domain = cookie['domain'],
domain_specified = cookie['domain_specified'],
domain_initial_dot = cookie['domain_initial_dot'],
path = cookie['path'],
path_specified = cookie['path_specified'],
secure = cookie['secure'],
expires = cookie['expires'],
discard = cookie['discard'],
comment = cookie['comment'],
comment_url = cookie['comment_url'],
rest = cookie['rest'],
rfc2109 = cookie['rfc2109'],
)
cj.set_cookie(c)
return cj
def main():
# テスト用
cf = "login.cjar"
cj = cookielib.LWPCookieJar()
cj.load(cf)
cookies_jsonstring = cookiejar_to_jsonstring(cj)
cj2 = jsonstring_to_cookiejar(cookies_jsonstring)
print cj2
if __name__ in '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment