Cookie and ShelveΒΆ

A sample of how to make cookies and shelve work together keeping session state at the server side:

#!/usr/bin/env python
import sha, time, Cookie, os, shelve

cookie = Cookie.SimpleCookie()
string_cookie = os.environ.get('HTTP_COOKIE')

if not string_cookie:
    sid = sha.new(repr(time.time())).hexdigest()
    cookie['sid'] = sid
    message = 'New session'
else:
    cookie.load(string_cookie)
    sid = cookie['sid'].value
cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60

# The shelve module will persist the session data
# and expose it as a dictionary
session_dir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session'
session = shelve.open('%s/sess_%s' % (session_dir, sid), writeback=True)

# Retrieve last visit time from the session
lastvisit = session.get('lastvisit')
if lastvisit:
    message = 'Welcome back. Your last visit was at ' + \
      time.asctime(time.gmtime(float(lastvisit)))
# Save the current time in the session
session['lastvisit'] = repr(time.time())

print """\
%s
Content-Type: text/html\n
<html><body>
<p>%s</p>
<p>SID = %s</p>
</body></html>
""" % (cookie, message, sid)

It first checks if there is a cookie already set. If not it creates a SID and attributes it to the cookie value. An expiration time of one year is established.

The lastvisit data is what is maintained in the session.

CGI Tutorial

  • Introduction
  • Hello World
  • Debugging
  • Form
  • Cookies
  • Session
    • Cookie Based SID
    • Query String SID
    • Hidden Field SID
    • The shelve module
    • Cookie and Shelve
    • A Session Class

Navigation

  • next
  • previous |
  • CGI Tutorial »
  • Session »
©2006-2015, Clodoaldo Pinto Neto.