检查会话cookie是否仍然存在(Python)

时间:2011-09-11 07:55:02

标签: python session-cookies urllib cookiejar cookielib

请查看以下 python 代码段:

import cookielib, urllib, urllib2

def login(username, password):
    cookie_jar = cookielib.LWPCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
    login = urllib.urlencode({'username': username, 'password': password})
    try:
        login_data = opener.open("http://www.example.com/login.php", login).read()
    except IOError:
        return 'Network Error'

    # on successful login the I'm storing the 'SESSION COOKIE'
    # that the site sends on a local file called cookie.txt

    cookie_jar.save('./cookie.txt', True, True)
    return login_data

# this method is called after quite sometime
# from calling the above method "login" 

def re_accessing_the _site():
    cookie_jar = cookielib.LWPCookieJar()

    # Here I'm re-loading the saved cookie
    # from the file to the cookie jar

    cookie_jar.revert('./cookie.txt', True, True)

    # there's only 1 cookie in the cookie jar
    for Cookie in cookie_jar:
        print 'Expires : ', Cookie.expires  ## prints None
        print 'Discard : ', Cookie.discard  ## prints True , means that the cookie is a
                                            ## session cookie
        print 'Is Expired : ', Cookie.is_expired()  ## prints False

    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
    try:
        data = opener.open("http://www.example.com/send.php")

        # Sometimes the opening fails as the cookie has expired
        # & sometimes it doesn't. Here I want a way to determine
        # whether the (session) cookie is still alive

    except IOError:
        return False
    return True

首先我打电话给登录&将检索到的Cookie(会话Cookie )保存到名为 cookie.txt 的本地文件中。 接下来很长一段时间( 15-20分钟)我正在调用另一种方法 re_accessing_the _site 。这次我还将以前保存的cookie重新加载到cookie jar中。 有时它工作正常,但有时会阻止我访问(会话cookie已过期)。所以我需要的是一种在通话过程中检查cookie是否仍然存在的方法......

0 个答案:

没有答案