<s> from __future__ import absolute_import <EOL> import logging <EOL> import redis <EOL> import time <EOL> from contextlib import contextmanager <EOL> from random import random <EOL> from . container import Container <EOL> class UnableToGetLock ( Exception ) : <EOL> pass <EOL> class _Redis ( object ) : <EOL> def __init__ ( self , app , options ) : <EOL> self . app = app <EOL> self . redis = redis . from_url ( app . config [ '<STR_LIT>' ] ) <EOL> self . logger = logging . getLogger ( app . name + '<STR_LIT>' ) <EOL> def __getattr__ ( self , name ) : <EOL> return getattr ( self . redis , name ) <EOL> @ contextmanager <EOL> def lock ( self , lock_key , expire = None , blocking_timeout = <NUM_LIT:3> , nowait = False ) : <EOL> """<STR_LIT>""" <EOL> conn = self . redis <EOL> if expire is None : <EOL> expire = blocking_timeout <EOL> delay = <NUM_LIT> + random ( ) / <NUM_LIT:10> <EOL> lock = conn . lock ( lock_key , timeout = expire , sleep = delay ) <EOL> acquired = lock . acquire ( blocking = not nowait , blocking_timeout = blocking_timeout ) <EOL> start = time . time ( ) <EOL> self . logger . info ( '<STR_LIT>' , lock_key ) <EOL> if not acquired : <EOL> raise UnableToGetLock ( '<STR_LIT>' % ( lock_key , ) ) <EOL> try : <EOL> yield <EOL> finally : <EOL> self . logger . info ( '<STR_LIT>' , lock_key ) <EOL> try : <EOL> lock . release ( ) <EOL> except Exception : <EOL> self . logger . exception ( "<STR_LIT>" , lock_key , time . time ( ) - start ) <EOL> def incr ( self , key ) : <EOL> self . redis . incr ( key ) <EOL> def decr ( self , key ) : <EOL> self . redis . decr ( key ) <EOL> def Redis ( ** o ) : <EOL> return Container ( _Redis , o , name = '<STR_LIT>' ) </s>
