<s> import binascii <EOL> import datetime <EOL> try : <EOL> import cPickle as pickle <EOL> except ImportError : <EOL> import pickle <EOL> import os <EOL> import time <EOL> class Session : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , sessiondb , max_age = <NUM_LIT:10> * <NUM_LIT> , datetime_fmt = "<STR_LIT>" , prepare_data = None ) : <EOL> """<STR_LIT>""" <EOL> self . sessiondb = sessiondb <EOL> self . datetime_fmt = datetime_fmt <EOL> self . max_age = max_age <EOL> self . prepare_data = prepare_data <EOL> if not self . sessiondb . get ( '<STR_LIT>' , None ) : <EOL> self . newid ( ) <EOL> if not self . sessiondb . get ( '<STR_LIT>' , None ) : <EOL> self . update_expdate ( ) <EOL> def getdata ( self ) : <EOL> "<STR_LIT>" <EOL> exp = self . sessiondb . get ( '<STR_LIT>' , None ) <EOL> if not exp : <EOL> return None <EOL> if type ( exp ) is datetime . datetime : <EOL> expdate = exp <EOL> elif type ( exp ) in ( str , unicode ) : <EOL> expdate = datetime . datetime . fromtimestamp ( time . mktime ( time . strptime ( exp , self . datetime_fmt ) ) ) <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" % self . datetime_fmt ) <EOL> if expdate < datetime . datetime . now ( ) : <EOL> return None <EOL> else : <EOL> if self . sessiondb [ '<STR_LIT>' ] : <EOL> strdata = str ( self . sessiondb [ '<STR_LIT>' ] ) <EOL> data = pickle . loads ( strdata ) <EOL> return data <EOL> else : <EOL> return None <EOL> def setdata ( self , data ) : <EOL> strdata = pickle . dumps ( data ) <EOL> if self . prepare_data : <EOL> strdata = self . prepare_data ( strdata ) <EOL> self . sessiondb [ '<STR_LIT>' ] = strdata <EOL> def newid ( self ) : <EOL> sessid = binascii . hexlify ( os . urandom ( <NUM_LIT:12> ) ) <EOL> self . sessiondb [ '<STR_LIT>' ] = sessid <EOL> def getid ( self ) : <EOL> return self . sessiondb . get ( '<STR_LIT>' ) <EOL> def update_expdate ( self ) : <EOL> self . sessiondb [ '<STR_LIT>' ] = self . _getexpdate ( ) <EOL> def _getexpdate ( self ) : <EOL> now = datetime . datetime . now ( ) <EOL> exp = now + datetime . timedelta ( seconds = self . max_age ) <EOL> return exp . strftime ( self . datetime_fmt ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> DB = { } <EOL> s = Session ( DB , max_age = <NUM_LIT:2> ) <EOL> s . newid ( ) <EOL> s . setdata ( { '<STR_LIT:test>' : '<STR_LIT>' } ) <EOL> print "<STR_LIT>" , s . getdata ( ) <EOL> print "<STR_LIT>" <EOL> print "<STR_LIT>" <EOL> time . sleep ( <NUM_LIT:3> ) <EOL> print "<STR_LIT>" , s . getdata ( ) </s>
