1.11.5 Obtaining a Session

Once the environment is set up and we have obtained a Driver object named driver we need to create a Manager object. We do this as follows:

manager = web.session.manager(driver=driver, expire=100)

The web.session.manager() function also takes a range of parameters such as expire to set the length of time in seconds the session is valid for or cookie to set the cookie options. The full list of options is listed in the API reference section but the default values are usually adequate. If you have not already created a driver it is possible to specify the driver() method's parameters in the manager() method and a driver will be created for you.

If we are using cookies to store session IDs we use the code Manager object to read the session ID of the current user from the cookie using the Manager object's session.cookieSessionID() method otherwise we obtain the session ID in whichever way is appropriate for our application.

sessionID = manager.cookieSessionID()

Once a session ID is obtained we can load the session. The Manager object's load() method will attempt to load a session from a session ID. If sessionID is not specified it will be obtained from a cookie. If the session is not valid or does not exist the method returns False and sets the error to the Manager object's error attribute.

If the session does not exist or has expired we need to create a new session using create(). This will also automatically send cookie headers to set the session ID unless session.create(sendCookieHeaders=False) is used, in which case you can still print the headers manually using sendCookieHeaders().

if not manager.load(sessionID):
    newSessionID = manager.create(sendCookieHeaders=False)
    manager.sendCookieHeaders()