Created
December 12, 2011 19:16
-
-
Save cablehead/1468645 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use it with something like.
import pymongo
conn = pymongo.Connection() # if your mongos is running on localhost
conn = AutoReconnectConnection(conn)