Managing User Sessions

plicitly close off the session, it would be automatically closed after a period of 60 seconds of inactivity, or whatever period was defined when the session was initiated. An implementation of the database cur- sor service for this example might be as follows.

class Cursor(netsvc.Service):

def __init__(self,name,cursor,timeout): netsvc.Service.__init__(self,name) self.joinGroup("database-services") self._cursor = cursor self._timeout = timeout self._restart() self.exportMethod(self.execute) self.exportMethod(self.executemany) self.exportMethod(self.description) self.exportMethod(self.rowcount) self.exportMethod(self.fetchone) self.exportMethod(self.fetchmany) self.exportMethod(self.fetchall) self.exportMethod(self.arraysize) self.exportMethod(self.close)

def encodeObject(self,object): if hasattr(MySQLdb,"DateTime"):

if type(object) == MySQLdb.DateTimeType: return ("xsd:string",object.strftime())

elif type(object) == MySQLdb.DateTimeDeltaType: return ("xsd:string",str(object))

return netsvc.Service.encodeObject(self,object) def executeMethod(self,name,method,params):

try:

return netsvc.Service.executeMethod(self,name,method,params) except MySQLdb.ProgrammingError,exception:

self.abortResponse(1,"Programming Error","db",str(exception)) except MySQLdb.Error,(error,description):

self.abortResponse(error,description,"mysql") def _restart(self):

self.cancelTimer("idle")

self.startTimer(self._expire,self._timeout,"idle") def _expire(self,name):

if name == "idle": self.close()

def execute(self,query,args=None):

result = self._cursor.execute(query,args) self._restart()

return result

# additional methods

def close(self): self._cursor.close()

117

Page 117
Image 117
Python 7.0pl5, Python Manual manual 117