<s> import bisect <EOL> import itertools <EOL> import random <EOL> from balancer . mixins import MasterSlaveMixin , PinningMixin <EOL> class BasePoolRouter ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> from django . conf import settings <EOL> if isinstance ( settings . DATABASE_POOL , dict ) : <EOL> self . pool = settings . DATABASE_POOL . keys ( ) <EOL> else : <EOL> self . pool = list ( settings . DATABASE_POOL ) <EOL> def allow_relation ( self , obj1 , obj2 , ** hints ) : <EOL> """<STR_LIT>""" <EOL> if obj1 . _state . db in self . pool and obj2 . _state . db in self . pool : <EOL> return True <EOL> return None <EOL> def allow_syncdb ( self , db , model ) : <EOL> """<STR_LIT>""" <EOL> return True <EOL> def allow_migrate ( self , db , model ) : <EOL> """<STR_LIT>""" <EOL> return True <EOL> class RandomRouter ( BasePoolRouter ) : <EOL> """<STR_LIT>""" <EOL> def db_for_read ( self , model , ** hints ) : <EOL> return self . get_random_db ( ) <EOL> def db_for_write ( self , model , ** hints ) : <EOL> return self . get_random_db ( ) <EOL> def get_random_db ( self ) : <EOL> return random . choice ( list ( self . pool ) ) <EOL> class WeightedRandomRouter ( RandomRouter ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> from django . conf import settings <EOL> self . pool = settings . DATABASE_POOL . keys ( ) <EOL> self . totals = [ ] <EOL> weights = settings . DATABASE_POOL . values ( ) <EOL> running_total = <NUM_LIT:0> <EOL> for w in weights : <EOL> running_total += w <EOL> self . totals . append ( running_total ) <EOL> def get_random_db ( self ) : <EOL> """<STR_LIT>""" <EOL> rnd = random . random ( ) * self . totals [ - <NUM_LIT:1> ] <EOL> pool_index = bisect . bisect_right ( self . totals , rnd ) <EOL> return list ( self . pool ) [ pool_index ] <EOL> class RoundRobinRouter ( BasePoolRouter ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> super ( RoundRobinRouter , self ) . __init__ ( ) <EOL> random . shuffle ( list ( self . pool ) ) <EOL> self . pool_cycle = itertools . cycle ( self . pool ) <EOL> def db_for_read ( self , model , ** hints ) : <EOL> return self . get_next_db ( ) <EOL> def db_for_write ( self , model , ** hints ) : <EOL> return self . get_next_db ( ) <EOL> def get_next_db ( self ) : <EOL> return next ( self . pool_cycle ) <EOL> class WeightedMasterSlaveRouter ( MasterSlaveMixin , WeightedRandomRouter ) : <EOL> pass <EOL> class RoundRobinMasterSlaveRouter ( MasterSlaveMixin , RoundRobinRouter ) : <EOL> pass <EOL> class PinningWMSRouter ( PinningMixin , WeightedMasterSlaveRouter ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> class PinningRRMSRouter ( PinningMixin , RoundRobinMasterSlaveRouter ) : <EOL> """<STR_LIT>""" <EOL> pass </s>
