<s> """<STR_LIT>""" <EOL> from heapq import heappush , heappop <EOL> from time import time <EOL> from hashlib import md5 <EOL> from random import random <EOL> class Session ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , session_id , expiry = None ) : <EOL> self . session_id = session_id <EOL> self . promoted = None <EOL> self . expiry = expiry <EOL> if self . expiry is not None : <EOL> self . expiry_date = time ( ) + self . expiry <EOL> def promote ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . expiry is not None : <EOL> self . promoted = time ( ) + self . expiry <EOL> def on_delete ( self , forced ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def __cmp__ ( self , other ) : <EOL> return cmp ( self . expiry_date , other . expiry_date ) <EOL> def __repr__ ( self ) : <EOL> return '<STR_LIT>' % ( getattr ( self , '<STR_LIT>' , - <NUM_LIT:1> ) , <EOL> self . session_id , <EOL> self . promoted or <NUM_LIT:0> ) <EOL> def _random_key ( ) : <EOL> """<STR_LIT>""" <EOL> i = md5 ( ) <EOL> i . update ( '<STR_LIT>' % ( random ( ) , time ( ) ) ) <EOL> return i . hexdigest ( ) <EOL> class SessionContainer ( object ) : <EOL> def __init__ ( self ) : <EOL> self . _items = dict ( ) <EOL> self . _queue = [ ] <EOL> def create ( self , session , expiry = None , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> kwargs [ '<STR_LIT>' ] = _random_key ( ) <EOL> kwargs [ '<STR_LIT>' ] = expiry <EOL> session = session ( ** kwargs ) <EOL> self . _items [ session . session_id ] = session <EOL> if expiry is not None : <EOL> heappush ( self . _queue , session ) <EOL> return session <EOL> def get ( self , session_id ) : <EOL> """<STR_LIT>""" <EOL> return self . _items . get ( session_id , None ) <EOL> def remove ( self , session_id ) : <EOL> """<STR_LIT>""" <EOL> session = self . _items . get ( session_id , None ) <EOL> if session is not None : <EOL> session . promoted = - <NUM_LIT:1> <EOL> session . on_delete ( True ) <EOL> return True <EOL> return False <EOL> def expire ( self , current_time = None ) : <EOL> """<STR_LIT>""" <EOL> if not self . _queue : <EOL> return <EOL> if current_time is None : <EOL> current_time = time ( ) <EOL> while self . _queue : <EOL> top = self . _queue [ <NUM_LIT:0> ] <EOL> if top . promoted is None and top . expiry_date > current_time : <EOL> break <EOL> top = heappop ( self . _queue ) <EOL> need_reschedule = ( top . promoted is not None <EOL> and top . promoted > current_time ) <EOL> if not need_reschedule : <EOL> top . promoted = None <EOL> top . on_delete ( False ) <EOL> need_reschedule = ( top . promoted is not None <EOL> and top . promoted > current_time ) <EOL> if need_reschedule : <EOL> top . expiry_date = top . promoted <EOL> top . promoted = None <EOL> heappush ( self . _queue , top ) <EOL> else : <EOL> del self . _items [ top . session_id ] </s>
