Decorator helper function to ensure some methods aren't needlessly called
    without an api_token configured.
498769
def api_token_required(f, *args, **kwargs):
    
    try:
        if args[0].api_token is None:
            raise AttributeError('Parameter api_token is required.')
    except AttributeError:
        raise AttributeError('Parameter api_token is required.')

    return f(*args, **kwargs)
1212195
def call_decorator(cls, func):
        

        @wraps(func)
        def _wrap(self, *args, **kwargs):
            try:
                return func(self, *args, **kwargs)
            except Exception:
                self.logger.exception('While executing benchmark')
                if not (self.catch_child_exception or False):
                    raise

        return _wrap
201697
def call_and_wrap(func, *args, **kw):
    '''
    '''
    try:
        return func(*args, **kw)
    except api.exceptions.APIException as ex:
        click_exception(ex)
    except urllib3exc.SSLError:
        # see monkey patch above re InsecurePlatformWarning
        if _insecure_warning:
            click.echo(click.style(str(_insecure_warning[0]), fg='red'))
        raise
1053866
def honeypot_exempt(view_func):
    
    # borrowing liberally from django's csrf_exempt
    def wrapped(*args, **kwargs):
        return view_func(*args, **kwargs)
    wrapped.honeypot_exempt = True
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped)
604434
def decorate_method(cls, func):
        
        func_args = [arg for arg in function_arguments(func) if arg != 'self']
        method_return_types = \
            Endpoint._parse_function_return_types_from_doc(func.__doc__)
        name = '%s.%s' % (cls.path, func.__name__)

        @wraps(func)
        def method_decorator(self, *args, **kwargs):
            for i in range(len(args)):
                kwargs[func_args[i]] = args[i]

            api_call = self.connection._pre_process_call(
                name, endpoint_params=kwargs)
            try:
                data = func(**kwargs)
            except RestException as e:
                api_call.error = e
                raise e

            except Exception as e:
                call_queue = self.connection._call_queue.get(
                    self.connection._get_thread_id(), [])
                if api_call in call_queue:
                    call_queue.remove(api_call)
                e = RestException(original_error=e,
                                  stack=traceback.format_exc())
                log.error('ApiCall Exception: %s' % e, exc_info=True)
                raise e
            return self.connection._post_process_call(
                api_call, data, method_return_types)

        method_decorator.rest_method = True
        return method_decorator
1140618
def api_call(fn):
    

    @wraps(fn)
    def wrapper(*args, **kwargs):
        try:
            result = fn(*args, **kwargs)
        except (DagobahError, DAGValidationError) as e:
            if request and request.endpoint == fn.__name__:
                return jsonify(error_type=type(e).__name__, message=e.message), 400
            raise e
        except Exception as e:
            logging.exception(e)
            raise e

        if request and request.endpoint == fn.__name__:
            status_code = None
            try:
                if result and '_status' in result:
                    status_code = result['_status']
                    del result['_status']
            except TypeError:
                pass

            if isinstance(result, dict):
                if 'result' in result:
                    return jsonify(status=status_code if status_code else 200,
                                   **result)
                else:
                    return jsonify(status=status_code if status_code else 200,
                                   result=result)
            else:
                return jsonify(status=status_code if status_code else 200,
                               result=result)

        else:
            return result

    return wrapper
152220
def require(self, lock, guard_func, *guard_args, **guard_kw):
        
        def decorator(f):
            @wraps(f)
            def wrapper(*args, **kw):
                if self.granted(lock):
                    self.msg('Granted {}'.format(lock))
                    return f(*args, **kw)
                if guard_func(*guard_args, **guard_kw) and self.acquire(lock):
                    return f(*args, **kw)
                return None
            return wrapper
        return decorator
245555
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        callerfunc = get_init(caller)
        doc = 'decorator(%s) converts functions/generators into ' \
            'factories of %s objects' % (caller.__name__, caller.__name__)
        fun = getfullargspec(callerfunc).args[1]  # second arg
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        callerfunc = caller
        doc = caller.__doc__
        fun = getfullargspec(callerfunc).args[0]  # first arg
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        callerfunc = caller.__call__.__func__
        doc = caller.__call__.__doc__
        fun = getfullargspec(callerfunc).args[1]  # second arg
    evaldict = callerfunc.__globals__.copy()
    evaldict['_call_'] = caller
    evaldict['_decorate_'] = decorate
    return FunctionMaker.create(
        '%s(%s)' % (name, fun),
        'return _decorate_(%s, _call_)' % fun,
        evaldict, call=caller, doc=doc, module=caller.__module__,
        __wrapped__=caller)
796797
def enabled_checker(func):
        
        @wraps(func)
        def wrap(self, *args, **kwargs):
            if self.allowed_methods and isinstance(self.allowed_methods, list) and func.__name__ not in self.allowed_methods:
                raise Exception("Method {} is disabled".format(func.__name__))
            return func(self, *args, **kwargs)
        return wrap
502295
def tokens_required(scopes='', new=False):
    

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):

            # if we're coming back from SSO for a new token, return it
            token = _check_callback(request)
            if token and new:
                tokens = Token.objects.filter(pk=token.pk)
                logger.debug("Returning new token.")
                return view_func(request, tokens, *args, **kwargs)

            if not new:
                # ensure user logged in to check existing tokens
                if not request.user.is_authenticated:
                    logger.debug(
                        "Session {0} is not logged in. Redirecting to login.".format(request.session.session_key[:5]))
                    from django.contrib.auth.views import redirect_to_login
                    return redirect_to_login(request.get_full_path())

                # collect tokens in db, check if still valid, return if any
                tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
                if tokens.exists():
                    logger.debug("Retrieved {0} tokens for {1} session {2}".format(tokens.count(), request.user,
                                                                                   request.session.session_key[:5]))
                    return view_func(request, tokens, *args, **kwargs)

            # trigger creation of new token via sso
            logger.debug("No tokens identified for {0} session {1}. Redirecting to SSO.".format(request.user, request.session.session_key[:5]))
            from esi.views import sso_redirect
            return sso_redirect(request, scopes=scopes)

        return _wrapped_view

    return decorator
269469
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
    
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            if current_user.is_authenticated:
                if request.is_json:
                    abort(HTTPStatus.FORBIDDEN)
                else:
                    if msg:
                        flash(msg, category)
                    return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
                                    override=redirect_url)
            return fn(*args, **kwargs)
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapper(decorator_args[0])
    return wrapper
635807
def jwt_required(realm=None):
    
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
            return fn(*args, **kwargs)
        return decorator
    return wrapper
1173079
def _hook_decorator(self, addr, length=0, kwargs=None):
        

        def hook_decorator(func):
            self.hook(addr, func, length=length, kwargs=kwargs)
            return func

        return hook_decorator
116978
def wrapper(self, updateParams=None):
		
		def decorator(f):
			_headers = self._getHeaders(updateParams)
			""" flask decorator to include headers """
			@wraps(f)
			def decorated_function(*args, **kwargs):
				resp = make_response(f(*args, **kwargs))
				self._setRespHeader(resp, _headers)
				resp.has_secure_headers = True
				return resp
			return decorated_function
		return decorator
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
805193
def _deprecated(func):
    """"""
    @wraps(func)
    def with_warning(*args, **kwargs):
        warnings.warn(
            ('The %s method is deprecated and will be removed in v2.*.*' %
             func.__name__),
            DeprecationWarning
        )
        return func(*args, **kwargs)
    return with_warning
38666
def pass_none(func):
	
	@functools.wraps(func)
	def wrapper(param, *args, **kwargs):
		if param is not None:
			return func(param, *args, **kwargs)
	return wrapper