Decorator to use on methods that are allowed
    to retry the request after reauthenticating the client.

    :param f: The original function
    :return: The decorated function
186965
def refresh_session_if_necessary(f):
    

    @functools.wraps(f)
    def wrapped(self, *args, **kwargs):
        try:
            result = f(self, *args, **kwargs)
        except Exception as ex:
            if hasattr(ex, 'code') and ex.code in (401, 403):
                self.refresh_session()
                # retry now
                result = f(self, *args, **kwargs)
            else:
                raise ex

        return result

    return wrapped
380752
def __retry_session(self, retries=10, backoff_factor=0.3,
                        status_forcelist=(500, 502, 504),
                        session=None):
        

        # requests.Session allows finer control, which is needed to use the
        # retrying code
        the_session = session or requests.Session()

        # The Retry object manages the actual retrying
        retry = Retry(total=retries, read=retries, connect=retries,
                      backoff_factor=backoff_factor,
                      status_forcelist=status_forcelist)

        adapter = HTTPAdapter(max_retries=retry)

        the_session.mount('http://', adapter)
        the_session.mount('https://', adapter)

        return the_session
86162
def _retry(function):
        

        def inner(self, **kwargs):
            last_exception = None
            #for host in self.router.get_hosts(**kwargs):
            for host in self.host:
                try:
                    return function(self, host, **kwargs)
                except SolrError as e:
                    self.logger.exception(e)
                    raise
                except ConnectionError as e:
                    self.logger.exception("Tried connecting to Solr, but couldn't because of the following exception.")
                    if '401' in e.__str__():
                        raise
                    last_exception = e
            # raise the last exception after contacting all hosts instead of returning None
            if last_exception is not None:
                raise last_exception
        return inner
659592
def wait_func_accept_retry_state(wait_func):
    """"""
    if not six.callable(wait_func):
        return wait_func

    if func_takes_retry_state(wait_func):
        return wait_func

    if func_takes_last_result(wait_func):
        @_utils.wraps(wait_func)
        def wrapped_wait_func(retry_state):
            warn_about_non_retry_state_deprecation(
                'wait', wait_func, stacklevel=4)
            return wait_func(
                retry_state.attempt_number,
                retry_state.seconds_since_start,
                last_result=retry_state.outcome,
            )
    else:
        @_utils.wraps(wait_func)
        def wrapped_wait_func(retry_state):
            warn_about_non_retry_state_deprecation(
                'wait', wait_func, stacklevel=4)
            return wait_func(
                retry_state.attempt_number,
                retry_state.seconds_since_start,
            )
    return wrapped_wait_func
125859
def login_required(function=None, message=None, login_url=None):
    
    actual_decorator = user_passes_test(
        lambda u: u.is_authenticated(),
        message=message,
        login_url=login_url
    )

    if function:
        return actual_decorator(function)
    return actual_decorator
684630
def require_sender(f):
    
    @wraps(f)
    def decorator(*args, **kwargs):
        if not request.authorization:
            return jsonify({'message': 'unauthorized'}), 401

        username = request.authorization.username
        password = request.authorization.password

        if not validate_sender(username, password):
            return jsonify({'message': 'forbidden'}), 403

        return f(*args, **kwargs)
    return decorator
473711
def _call_retry(self, force_retry):
        """"""
        last_exception = None
        for i in range(self.max_attempts):
            try:
                log.info("Calling %s %s" % (self.method, self.url))
                response = self.requests_method(
                    self.url,
                    data=self.data,
                    params=self.params,
                    headers=self.headers,
                    timeout=(self.connect_timeout, self.read_timeout),
                    verify=self.verify_ssl,
                )

                if response is None:
                    log.warn("Got response None")
                    if self._method_is_safe_to_retry():
                        delay = 0.5 + i * 0.5
                        log.info("Waiting %s sec and Retrying since call is a %s" % (delay, self.method))
                        time.sleep(delay)
                        continue
                    else:
                        raise PyMacaronCoreException("Call %s %s returned empty response" % (self.method, self.url))

                return response

            except Exception as e:

                last_exception = e

                retry = force_retry

                if isinstance(e, ReadTimeout):
                    # Log enough to help debugging...
                    log.warn("Got a ReadTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    resp = e.response
                    if not resp:
                        log.info("Requests error has no response.")
                        # TODO: retry=True? Is it really safe?
                    else:
                        b = resp.content
                        log.info("Requests has a response with content: " + pprint.pformat(b))
                    if self._method_is_safe_to_retry():
                        # It is safe to retry
                        log.info("Retrying since call is a %s" % self.method)
                        retry = True

                elif isinstance(e, ConnectTimeout):
                    log.warn("Got a ConnectTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    # ConnectTimeouts are safe to retry whatever the call...
                    retry = True

                if retry:
                    continue
                else:
                    raise e

        # max_attempts has been reached: propagate the last received Exception
        if not last_exception:
            last_exception = Exception("Reached max-attempts (%s). Giving up calling %s %s" % (self.max_attempts, self.method, self.url))
        raise last_exception
904464
def authorized_handler(self, f):
        
        @functools.wraps(f)
        def decorated():
            resp = self._handle_authorize_response()
            return f(resp)
        self._authorized_handler = decorated
        return decorated
1203909
def rest(f):
    

    @wraps(f)
    def wrapper(*args, **kwargs):
        ret = f(*args, **kwargs)
        if ret is None:
            response = '', 204
        elif isinstance(ret, current_app.response_class):
            response = ret
        elif isinstance(ret, tuple):
            # code, result_dict|msg_string
            if isinstance(ret[1], basestring):
                response = jsonify(msg=ret[1])
            else:
                response = jsonify(**ret[1])
            response.status_code = ret[0]
        else:
            response = jsonify(**ret)
        return response

    return wrapper
533334
def retry(max_retries=1):
    

    def retry_func(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            num_retries = 0
            while num_retries <= max_retries:
                try:
                    ret = func(*args, **kwargs)
                    break
                except HTTPError:
                    if num_retries == max_retries:
                        raise
                    num_retries += 1
                    time.sleep(5)
            return ret

        return wrapper

    return retry_func
77262
def api(func=None, timeout=API_TIMEOUT):  # incoming
    
    if func is None:
        return partial(api, timeout=timeout)
    else:
        wrapper = _get_api_decorator(func=func, timeout=timeout)
        return wrapper
1329452
def requires_auth(f):
    

    @wraps(f)
    def requires_auth_decorator(*args, **kwargs):

        try:
            authenticate_http_request()
        except PyMacaronException as e:
            return e.http_reply()

        return f(*args, **kwargs)

    return requires_auth_decorator
875394
def login_required(f):
    '''
    
    '''
    def _wrapper(self, *args, **kwargs):
        '''
        Function to be applied on top of all decorated methods
        '''
        if self._token_age:
            timediff = self._token_age - datetime.datetime.now()
            if timediff.total_seconds() / 60 > TOKEN_TIMEOUT:
                self.logout()  # Log out to invalidate previous token
                self.login()  # Request new token
        else:  # haven't logged in yet
            self.login()
        return f(self, *args, **kwargs)
    return _wrapper
176132
def retry(tries, delay=0, back_off=1, raise_msg=''):
    

    if back_off < 1:
        raise ValueError('back_off must be 1 or greater')

    tries = math.floor(tries)
    if tries < 0:
        raise ValueError('tries must be 0 or greater')

    if delay < 0:
        raise ValueError('delay must be 0 or greater')

    def deco_retry(f):
        def f_retry(*args, **kwargs):
            max_tries, max_delay = tries, delay  # make mutable

            while max_tries > 0:
                rv = f(*args, **kwargs)  # first attempt
                if rv:  # Done on success
                    return rv

                max_tries -= 1  # consume an attempt
                time.sleep(max_delay)  # wait...
                max_delay *= back_off  # make future wait longer
            else:
                if raise_msg:
                    raise Exception(raise_msg)
                return

        return f_retry  # true decorator -> decorated function

    return deco_retry
110627
function onceify(f) {
  var ran, ret;
  return function() {
    return ran ? ret : (ran=true, ret=f.apply(this,arguments));
  };
}
1145483
def request(method, url, **kwargs):
    
    retries = kwargs.pop('retries', None)
    with Session(retries=retries) as session:
        return session.request(method=method, url=url, **kwargs)
969881
def repeat_call(func, retries, *args, **kwargs):
    '''
    
    '''
    retries = max(0, int(retries))
    try_num = 0
    while True:
        if try_num == retries:
            return func(*args, **kwargs)
        else:
            try:
                return func(*args, **kwargs)
            except Exception as e:
                if isinstance(e, KeyboardInterrupt):
                    raise e
                try_num += 1