-
-
Save RobertWang/e97ed65087c7f79114a9e1aa57e76639 to your computer and use it in GitHub Desktop.
Gracefully handle a PyMongo AutoReconnect
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment