读取curl创建的cookie文件 [英] reading cookies file created by curl

查看:50
本文介绍了读取curl创建的cookie文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过curl保存了以下cookie(在test.txt中,用制表符分隔,此编辑器不保留制表符):

I have the following cookie saved by curl (in test.txt, tab-separated, this editor doesn't preserve tabs):

# Netscape HTTP Cookie File
# http://curlm.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_my-example.com    FALSE   /   FALSE   0   _rails-root_session test

我正在尝试使用以下代码阅读它:

I'm trying to read it with the following code:

import sys

if sys.version_info < (3,):
    from cookielib import Cookie, MozillaCookieJar
else:
    from http.cookiejar import Cookie, MozillaCookieJar

def load_cookies_from_mozilla(filename):
    ns_cookiejar = MozillaCookieJar()
    ns_cookiejar.load(filename, ignore_discard=True)
    return ns_cookiejar

cookies = load_cookies_from_mozilla("test.txt")
print (len(cookies))

它输出0(无法读取cookie).如果我手动将cookie修改为以下行(删除HttpOnly标志,并将0更改为空字符串以使其过期,然后再次制表符分隔):

It outputs 0 (unable to read the cookie). If I manually modify my cookie to the following line (remove HttpOnly flag and changing 0 to the empty string for expiration time, and again, tab-separated):

my-example.com  FALSE   /   FALSE       _rails-root_session test

然后输出1(成功读取cookie).

then it outputs 1 (successfully read the cookie).

需要什么操作才能读取原始cookie行的python代码?并且最好能够将其保存为相同的格式(使用HttpOnly标志并用0代替永不过期的cookie的空字符串)?

What needs to be done to my python code to read the original cookie line? And preferably to be able to save it in the same format (with HttpOnly flag and with 0 instead of empty string for never-expiring cookie)?

谢谢.

推荐答案

这似乎是一个打开的错误: https://bugs.python.org/issue2190 .

This appears to be an open bug: https://bugs.python.org/issue2190.

此错误报告包含解决方法的链接: https://gerrit.googlesource.com/git-repo/+/master/subcmds/sync.py#995

This bug report contains a link to a workaround: https://gerrit.googlesource.com/git-repo/+/master/subcmds/sync.py#995

在该链接的代码中,开发人员创建一个临时cookie文件,删除"#HttpOnly_"前缀,然后使用该临时文件创建一个cookiejar.

In that linked code, the developer creates a temporary cookies file, removes the "#HttpOnly_" prefixes, and then creates a cookiejar with that temporary file.

tmpcookiefile = tempfile.NamedTemporaryFile()
tmpcookiefile.write("# HTTP Cookie File")
try:
  with open(cookiefile) as f:
    for line in f:
      if line.startswith("#HttpOnly_"):
       line = line[len("#HttpOnly_"):]
      tmpcookiefile.write(line)
  tmpcookiefile.flush()
  cookiejar = cookielib.MozillaCookieJar(tmpcookiefile.name)
  try:
    cookiejar.load()
  except cookielib.LoadError:
    cookiejar = cookielib.CookieJar()
finally:
  tmpcookiefile.close()

这篇关于读取curl创建的cookie文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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