<s> import datetime <EOL> import logging <EOL> import time <EOL> from django . conf import settings <EOL> from common import clock <EOL> from common import exception <EOL> from common import memcache <EOL> utcnow = lambda : clock . utcnow ( ) <EOL> def _d2t ( dt ) : <EOL> return time . mktime ( dt . timetuple ( ) ) <EOL> BUCKETS = { '<STR_LIT>' : lambda : _d2t ( utcnow ( ) ) + <NUM_LIT> , <EOL> '<STR_LIT>' : lambda : _d2t ( utcnow ( ) ) + <NUM_LIT> * <NUM_LIT> , <EOL> '<STR_LIT>' : lambda : _d2t ( utcnow ( ) ) + <NUM_LIT> * <NUM_LIT> * <NUM_LIT> , <EOL> '<STR_LIT>' : lambda : _d2t ( utcnow ( ) ) + <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:30> , <EOL> } <EOL> def throttle_key ( actor_ref , action , bucket ) : <EOL> nick = '<STR_LIT>' <EOL> if actor_ref : <EOL> nick = actor_ref . nick <EOL> return '<STR_LIT>' % ( nick , action , bucket ) <EOL> def throttle ( actor_ref , action , ** kw ) : <EOL> """<STR_LIT>""" <EOL> if actor_ref and actor_ref . nick == settings . ROOT_NICK : <EOL> return <EOL> already_throttled = False <EOL> for k , v in kw . iteritems ( ) : <EOL> if k in BUCKETS : <EOL> throttled = throttle_status ( actor_ref , action , bucket = k , max = v ) <EOL> if throttled and not already_throttled : <EOL> already_throttled = k <EOL> if not throttled : <EOL> throttle_inc ( actor_ref , action , bucket = k ) <EOL> if already_throttled : <EOL> raise exception . ApiThrottled ( <EOL> '<STR_LIT>' % already_throttled ) <EOL> def throttle_status ( actor_ref , action , bucket , max ) : <EOL> """<STR_LIT>""" <EOL> cache_key = throttle_key ( actor_ref , action , bucket ) <EOL> count = memcache . client . get ( cache_key ) <EOL> if count >= max : <EOL> return True <EOL> return False <EOL> def throttle_inc ( actor_ref , action , bucket ) : <EOL> timeout = BUCKETS [ bucket ] ( ) <EOL> cache_key = throttle_key ( actor_ref , action , bucket ) <EOL> memcache . client . add ( cache_key , <NUM_LIT:0> , timeout ) <EOL> memcache . client . incr ( cache_key ) </s>
