我正在使用python和cookielib与日期设置不正确的超文本传输协议服务器通信。我无法控制这个服务器,所以不可能固定它的时间。不幸的是,服务器的错误时间搞乱了cookielib,因为cookie似乎已经过期了。
有趣的是,如果我使用任何web浏览器访问同一网站,浏览器都会接受cookie并将其保存。我假设现代web浏览器总是遇到配置错误的web服务器,并且看到它们的Date头设置不正确,并相应地调整cookie过期日期。
以前有没有人遇到过这个问题?在Python中有什么方法可以处理它吗?

发布于 2016-11-18 02:46:57
我想出了一个解决方案,其中包括对urllib库进行活体猴子补丁。当然不是很理想,但如果其他人找到更好的方法,请让我知道:
cook_proc = urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar())
cookie_processing_lock = threading.Lock()
def _process_cookies(request, response):
'''Process cookies, but do so in a way that can handle servers with bad
clocks set.'''
# We do some real monkey hacking here, so put it in a lock.
with cookie_processing_lock:
# Get the server date.
date_header = cookielib.http2time(
response.info().getheader('Date') or '')
# Save the old cookie parsing function.
orig_parse = cookielib.parse_ns_headers
# If the server date is off by more than an hour, we'll adjust it.
if date_header:
off_by = time.time() - date_header
if abs(off_by) > 3600:
logging.warning("Server off %.1f hrs."%(abs(off_by)/3600))
# Create our monkey patched
def hacked_parse(ns_headers):
try:
results = orig_parse(ns_headers)
for r in results:
for r_i, (key, val) in enumerate(r):
if key == 'expires':
r[r_i] = key, val + off_by
logging.info("Fixing bad cookie "
"expiration time for: %s"%r[0][0])
logging.info("COOKIE RESULTS: %s", results)
return results
except Exception as e:
logging.error("Problem parse cookie: %s"%e)
raise
cookielib.parse_ns_headers = hacked_parse
response = cook_proc.http_response(request, response)
# Make sure we set the cookie processor back.
cookielib.parse_ns_headers = orig_parsehttps://stackoverflow.com/questions/40568526
复制相似问题