[mod_python] RE: Session handling: example needed

Christoph Spoerri spoerri at duke.edu
Thu Jan 8 10:33:40 EST 2004


Hi list users,

I saw that recently somebody added for an example of using the session 
handler. I was looking for the same with out any luck, but was able to get 
things working (love the trial-and-error stuff ;) ).

I have attached a short script that uses two counters (int and object) to 
count the number of visits by the users during a session.

Notes:
- use is_new() to check if you have a new session or not before you use it (as 
mentioned in the manual)
- you need to save the session object at the end otherwise, the ID and any 
other stuff won't be saved (!), and you'll be wondering what happend to the 
session (as I did).

cheers,
Christoph

PS: I'm new to python, so forgive me any strange python coding.

***************** session_sample.py ***********************

from mod_python import apache

class simpelCountClass:
	count = 0
	def __init__(self,c):
		self.count = c
	def increment(self):
		self.count = self.count+1
	def asString(self):
		return str(self.count)


def sessionTest(req):
	req.content_type = "text/html"
	s = "<html><body>testing<br>"

	t = Session.DbmSession(req)
	if (t.is_new()):
		s += "new session id: "+str(t.id())+"<br>"
		t['count']=1
		t['countObj']=simpelCountClass(1)

	else:
		s += "session id: "+str(t.id())+"<br>"
		t['count']=t['count']+1
		t['countObj'].increment()

	s += "count: "+str(t['count'])+"<br>"
	s += "countObj: "+t['countObj'].asString()+"<br>"
	s += "timeout: "+str(t.timeout())+"<br>"
	s += "created: "+str(t.created())+"<br>"
	s += "last_accessed: "+str(t.last_accessed())+"<br>"
	s += "</body></html>"
	t.save() # DON'T FORGET THIS ONE!!!
	return s



More information about the Mod_python mailing list