Skip to content

Instantly share code, notes, and snippets.

@anthonywu
Created January 29, 2012 01:25
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save anthonywu/1696591 to your computer and use it in GitHub Desktop.
Save anthonywu/1696591 to your computer and use it in GitHub Desktop.
Gracefully handle a PyMongo AutoReconnect
import functools
import pymongo
import logging
import time
MAX_AUTO_RECONNECT_ATTEMPTS = 5
def graceful_auto_reconnect(mongo_op_func):
"""Gracefully handle a reconnection event."""
@functools.wraps(mongo_op_func)
def wrapper(*args, **kwargs):
for attempt in xrange(MAX_AUTO_RECONNECT_ATTEMPTS):
try:
return mongo_op_func(*args, **kwargs)
except pymongo.errors.AutoReconnect as e:
wait_t = 0.5 * pow(2, attempt) # exponential back off
logging.warning("PyMongo auto-reconnecting... %s. Waiting %.1f seconds.", str(e), wait_t)
time.sleep(wait_t)
return wrapper
@lucian1900
Copy link

Interesting. I'm building something similar by subclassing pymongo.connection.Connection. However, I'm having trouble with it looping forever between 0 and 1 tries. I tried this https://gist.github.com/1057236 with the same result.

What exactly is mongo_op_func here, if you don't mind?

@ahmedtalhakhan
Copy link

Might want to look at this https://github.com/arngarden/MongoDBProxy. Its pretty cool and gets incorporated into existing code with minimal changes.

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