Skip to content

Instantly share code, notes, and snippets.

@rbdcti
Created February 2, 2012 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbdcti/1723790 to your computer and use it in GitHub Desktop.
Save rbdcti/1723790 to your computer and use it in GitHub Desktop.
mongoengine reconnect
from pymongo.cursor import Cursor
from pymongo.connection import Connection
from pymongo.errors import AutoReconnect
import pymongo
import time
import functools
import logging
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):
attempt = 0
print "WRAPPER ENTRY"
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
print "PyMongo auto-reconnecting... %s. Waiting %.1f seconds. (Attempt %i)" % (str(e), wait_t, attempt)
if attempt >= 5:
print "MAX ATTEMPTS REACHED"
raise
time.sleep(wait_t)
print "WRAPPER EXIT"
return wrapper
print "SETTING OVERRIDES"
Cursor._Cursor__send_message = graceful_auto_reconnect(Cursor._Cursor__send_message)
Connection._send_message = graceful_auto_reconnect(Connection._send_message)
Connection._send_message_with_response = graceful_auto_reconnect(Connection._send_message_with_response)
#Connection._Connection__find_master = reconnect(Connection._Connection__find_master)
print "SETTING OVERRIDES DONE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment