Decorator for automatic handling of AutoReconnect-exceptions.

def safe_mongocall(call):
    """ Decorator for automatic handling of AutoReconnect-exceptions.
    """

    def _safe_mongocall(*args, **kwargs):
        for i in range(4):
            try:
                return call(*args, **kwargs)
            except pymongo.errors.AutoReconnect:
                print ('AutoReconnecting, try %d' % i)
                time.sleep(pow(2, i))
        # Try one more time, but this time, if it fails, let the
        # exception bubble up to the caller.
        return call(*args, **kwargs)
    return _safe_mongocall