2

Please take a look at the following python code snippet :

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

First I'm calling the method login & saves the retrieved cookie (which is a session cookie)to a local file called cookie.txt. Next after quite sometime (15-20 mins) I'm calling the other method re_accessing_the _site . This time I'm also re loading the previously saved cookie into the cookie jar. Sometimes it's working fine but sometimes it's blocking me to access (as the session cookie has expired) . So all I need is a way to check whether the cookie is still alive during the call ...

dexter
  • 21
  • 1
  • 3
  • 1
    It's possible that the timestamp of the authentication is in the data in the cookie, or even held server-side. In which case there may be no way to know by interrogating the Cookie object. If this is the case then you'll just have to cache the username/password yourself, catch the error, log in again and retry. Just out of interest, can you paste Cookie.__dict__ in here as it might have more useful info somewhere... – ed. Sep 11 '11 at 23:01

0 Answers0