Skip to content

Instantly share code, notes, and snippets.

@cablehead
Created December 12, 2011 19:16
Show Gist options
  • Save cablehead/1468645 to your computer and use it in GitHub Desktop.
Save cablehead/1468645 to your computer and use it in GitHub Desktop.
# autoreconnect handling
def autoreconnect(f, *a, **kw):                                                                
   max_tries = 12                                                                              
   num_tries = 1                                                                              
   while True:                                                                                
       try:
           return f(*a, **kw)
       except pymongo.errors.AutoReconnect, e:                                                
           logging.warning(
               'MONGO-AUTORECONNECT attempt=%s' % num_tries, exc_info=True)                    
           num_tries += 1
           if num_tries > max_tries:                                                          
               raise
           time.sleep(0.1*num_tries)                                                          
                                                                                               
class AutoReconnectCallable(object):                                                            
   def __init__(self, method):                                                                
       self.method = method                                                                    
   
   def __call__(self, *a, **kw):
       return autoreconnect(self.method, *a, **kw)                                            
                                                                                               
class AutoReconnectConnection(object):                                                          
   def __init__(self, target):                                                                
       self.__target = target                                                                  
   
   def __getattr__(self, name):
       ob = getattr(self.__target, name, None)                                                
       if ob == None:
           return self.__getitem__(name)                                                      
       if callable(ob):
           return AutoReconnectCallable(ob)                                                    
       return ob                                                                              
   
   def __getitem__(self, name):
       return AutoReconnectConnection(self.__target.__getattr__(name))          
@cablehead
Copy link
Author

You can use it with something like.

import pymongo
conn = pymongo.Connection() # if your mongos is running on localhost
conn = AutoReconnectConnection(conn)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment