1.11.4 Loading a Session

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 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()

If you are using a CGI environment all this code can be simplified to just the following:

if not manager.load():
    newSessionID = manager.create()

The load() method obtains a session ID automatically if not present and create() automatically sends the headers.