首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置了错误日期/时区的HTTP服务器的Python Cookielib

设置了错误日期/时区的HTTP服务器的Python Cookielib
EN

Stack Overflow用户
提问于 2016-11-13 06:44:39
回答 1查看 58关注 0票数 0

我正在使用python和cookielib与日期设置不正确的超文本传输协议服务器通信。我无法控制这个服务器,所以不可能固定它的时间。不幸的是,服务器的错误时间搞乱了cookielib,因为cookie似乎已经过期了。

有趣的是,如果我使用任何web浏览器访问同一网站,浏览器都会接受cookie并将其保存。我假设现代web浏览器总是遇到配置错误的web服务器,并且看到它们的Date头设置不正确,并相应地调整cookie过期日期。

以前有没有人遇到过这个问题?在Python中有什么方法可以处理它吗?

EN

回答 1

Stack Overflow用户

发布于 2016-11-18 02:46:57

我想出了一个解决方案,其中包括对urllib库进行活体猴子补丁。当然不是很理想,但如果其他人找到更好的方法,请让我知道:

代码语言:javascript
复制
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_parse
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40568526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档