Using Sessions

Unlike cookies, session information is always stored on the server and is not communicated back to the user. Consequently, sessions have several advantages over cookies, and the uses of sessions may include the storage of...

WebStack API - Using Sessions

In WebStack, a session appears as a dictionary to applications and is acquired for a specific user through the transaction object. The following methods are provided in the transaction for accessing and maintenance of session information:

get_session
This method returns the session for the identified user. The create parameter can be set to a true value to create a new session for a user if no session previously existed; otherwise None is returned in such situations.
expire_session
This method causes the session information associated with the identified user to be forgotten. Note that this may not really happen until the user sends another request, and that the get_session method may still return the current session.

Session objects, which resemble dictionaries, employ plain Python strings as keys in the accessing of information, and as the values loaded and stored inside the session. Unlike cookies, upon setting information within a session, such information is remembered thereafter without any other actions being necessary to make that information permanent or persistent.

How and When to Access Sessions

To find out if a session has already been created, ask for a session by specifying that one should not be automatically created:

        # In the respond method...
session = trans.get_session(create=0) # session is None if no session already exists

To ensure that a session exists, just ask for a session:

        # In the respond method...
session = trans.get_session() # this is the same as using create=1

Session contents may mostly be accessed like dictionaries, so to access the keys within a session the following code could be used:

        # In the respond method after obtaining a session...
for key in session.keys():
[Do something with the key - perhaps obtain values.]

To test the presence of a key, and to access values associated with a key, the usual dictionary methods apply:

        # In the respond method after obtaining the session...
if session.has_key("my_data"):
my_data = session["my_data"]
[Do something with my_data.]
session["my_data"] = my_data

The session for the user may be removed or "expired" as follows:

        # In the respond method...
trans.expire_session()

Note that WebStack automatically knows which session is to be expired since only one such session can exist for the identified user.

Session Limitations and Guidelines