Python functools.wraps() Examples

The following are 30 code examples for showing how to use functools.wraps(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module functools , or try the search function .

Example 1
Project: aegea   Author: kislyuk   File: decorators.py    License: Apache License 2.0 6 votes vote down vote up
def requires_auth(func):
    """Decorator to note which object methods require authorization."""
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        auth = False
        if hasattr(self, '_session'):
            auth = (self._session.auth or
                    self._session.headers.get('Authorization'))

        if auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper 
Example 2
Project: aegea   Author: kislyuk   File: decorators.py    License: Apache License 2.0 6 votes vote down vote up
def requires_basic_auth(func):
    """Specific (basic) authentication decorator.

    This is used to note which object methods require username/password
    authorization and won't work with token based authorization.

    """
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        if hasattr(self, '_session') and self._session.auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires username/password authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper 
Example 3
Project: aegea   Author: kislyuk   File: decorators.py    License: Apache License 2.0 6 votes vote down vote up
def requires_app_credentials(func):
    """Require client_id and client_secret to be associated.

    This is used to note and enforce which methods require a client_id and
    client_secret to be used.

    """
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        client_id, client_secret = self._session.retrieve_client_credentials()
        if client_id and client_secret:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires username/password authentication"}'
            )
            raise GitHubError(r)

    return auth_wrapper 
Example 4
def s3_request(func: Callable):
    """
    Wrapper function for s3 requests in order to create more helpful error
    messages.
    """

    @wraps(func)
    def wrapper(url: str, *args, **kwargs):
        try:
            return func(url, *args, **kwargs)
        except ClientError as exc:
            if int(exc.response["Error"]["Code"]) == 404:
                raise FileNotFoundError("file {} not found".format(url))
            else:
                raise

    return wrapper 
Example 5
Project: everyclass-server   Author: everyclass   File: api_helpers.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def token_required(func):
    """
    检查是否携带token,如果token未携带或无效将直接返回错误,否则将username保存到g.username中
    """
    from everyclass.server.user import service as user_service

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        token = request.headers.get("X-API-Token")
        if not token:
            return generate_error_response(None, STATUS_CODE_TOKEN_MISSING)

        username = user_service.get_username_from_jwt(token)
        if not username:
            return generate_error_response(None, STATUS_CODE_INVALID_TOKEN)

        g.username = username
        return func(*args, **kwargs)

    return wrapped 
Example 6
Project: everyclass-server   Author: everyclass   File: api_helpers.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def login_required(func):
    """检查用户是否已登录,如未登录则返回错误"""

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        try:
            ut, uid = get_ut_uid()
            if ut == UTYPE_GUEST:
                return generate_error_response(None, STATUS_CODE_PERMISSION_DENIED, "您需要登录才能进行此操作")
        except NotImplementedError:
            return generate_error_response(None, STATUS_CODE_PERMISSION_DENIED, "检测身份时遇到未知错误")

        g.user_id = uid
        return func(*args, **kwargs)

    return wrapped 
Example 7
Project: Flask-pyoidc   Author: zamzterz   File: flask_pyoidc.py    License: Apache License 2.0 6 votes vote down vote up
def oidc_logout(self, view_func):
        self._logout_view = view_func

        @functools.wraps(view_func)
        def wrapper(*args, **kwargs):
            if 'state' in flask.request.args:
                # returning redirect from provider
                if flask.request.args['state'] != flask.session.pop('end_session_state'):
                    logger.error("Got unexpected state '%s' after logout redirect.", flask.request.args['state'])
                return view_func(*args, **kwargs)

            redirect_to_provider = self._logout()
            if redirect_to_provider:
                return redirect_to_provider

            return view_func(*args, **kwargs)

        return wrapper 
Example 8
Project: eve-auth-jwt   Author: rs   File: auth.py    License: MIT License 6 votes vote down vote up
def requires_token(self, audiences=None, allowed_roles=None):
        """
        Decorator for functions that will be protected with token authentication.

        Token must be provvided either through access_token parameter or Authorization
        header.

        See check_token() method for further details.
        """
        def requires_token_wrapper(f):
            @wraps(f)
            def decorated(*args, **kwargs):
                try:
                    token = request.args['access_token']
                except KeyError:
                    token = request.headers.get('Authorization', '').partition(' ')[2]

                if not self._perform_verification(token, audiences, allowed_roles):
                    abort(401)

                return f(*args, **kwargs)
            return decorated
        return requires_token_wrapper 
Example 9
Project: multibootusb   Author: mbusb   File: discover.py    License: GNU General Public License v2.0 6 votes vote down vote up
def wrap_exception(func):
    """
    Allow Device discovery methods to return None instead of raising an
    exception.
    """

    @functools.wraps(func)
    def the_func(*args, **kwargs):
        """
        Returns result of calling ``func`` on ``args``, ``kwargs``.
        Returns None if ``func`` raises :exc:`DeviceNotFoundError`.
        """
        try:
            return func(*args, **kwargs)
        except DeviceNotFoundError:
            return None

    return the_func 
Example 10
Project: friendly-telegram   Author: friendly-telegram   File: loader.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def translateable_docstring(cls):
    @functools.wraps(cls.config_complete)
    def config_complete(self, *args, **kwargs):
        for command, func in get_commands(cls).items():

            @functools.wraps(func)
            def replacement(*args, **kwargs):
                return func(self, *args, **kwargs)
            replacement.__doc__ = self.strings["_cmd_doc_" + command]
            setattr(self, command, replacement)
        self.__doc__ = self.strings["_cls_doc"]
        return self.config_complete._old_(self, *args, **kwargs)
    config_complete._old_ = cls.config_complete
    cls.config_complete = config_complete
    for command, func in get_commands(cls).items():
        cls.strings["_cmd_doc_" + command] = inspect.getdoc(func)
    cls.strings["_cls_doc"] = inspect.getdoc(cls)
    return cls 
Example 11
Project: comport   Author: codeforamerica   File: decorators.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def requires_roles(required_roles):
    '''
    Takes in a list of roles and checks whether the user
    has access to those role
    '''
    def check_roles(view_function):
        @wraps(view_function)
        def decorated_function(*args, **kwargs):
            def names(role):
                return role.name
            if not all(r in map(names, current_user.roles) for r in required_roles):
                flash('You do not have sufficient permissions to do that', 'alert alert-danger')
                return redirect(request.args.get('next') or '/')
            return view_function(*args, **kwargs)
        return decorated_function
    return check_roles 
Example 12
Project: comport   Author: codeforamerica   File: decorators.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def extractor_auth_required():
    '''
    Ensures that current_user is an extractor with access to the correct department
    '''
    def check_extractor(view_function):
        @wraps(view_function)
        def decorated_function(*args, **kwargs):
            username = request.authorization.username
            password = request.authorization.password

            found_extractor = Extractor.query.filter_by(username=username).first()

            if not found_extractor:
                return ("No extractor with that username!", 401)

            if not found_extractor.check_password(password):
                return ("Extractor authorization failed!", 401)

            return view_function(*args, **kwargs)
        return decorated_function
    return check_extractor 
Example 13
Project: DOTA_models   Author: ringringyi   File: scopes.py    License: Apache License 2.0 6 votes vote down vote up
def add_arg_scope(func):
  """Decorates a function with args so it can be used within an arg_scope.

  Args:
    func: function to decorate.

  Returns:
    A tuple with the decorated function func_with_args().
  """
  @functools.wraps(func)
  def func_with_args(*args, **kwargs):
    current_scope = _current_arg_scope()
    current_args = kwargs
    key_func = (func.__module__, func.__name__)
    if key_func in current_scope:
      current_args = current_scope[key_func].copy()
      current_args.update(kwargs)
    return func(*args, **current_args)
  _add_op(func)
  return func_with_args 
Example 14
Project: OpenFermion-Cirq   Author: quantumlib   File: _compat_test.py    License: Apache License 2.0 6 votes vote down vote up
def deprecated_test(test: Callable) -> Callable:
    """Marks a test as using deprecated functionality.

    Ensures the test is executed within the `pytest.deprecated_call()` context.

    Args:
        test: The test.

    Returns:
        The decorated test.
    """

    @functools.wraps(test)
    def decorated_test(*args, **kwargs) -> Any:
        with pytest.deprecated_call():
            test(*args, **kwargs)

    return decorated_test 
Example 15
Project: ssm-cache-python   Author: alexcasalboni   File: cache.py    License: MIT License 6 votes vote down vote up
def refresh_on_error(
            self,
            error_class=Exception,
            error_callback=None,
            retry_argument='is_retry'
        ):
        """ Decorator to handle errors and retries """
        if error_callback and not callable(error_callback):
            raise TypeError("error_callback must be callable")
        def true_decorator(func):
            """ Actual func wrapper """
            @wraps(func)
            def wrapped(*args, **kwargs):
                """ Actual error/retry handling """
                try:
                    return func(*args, **kwargs)
                except error_class:  # pylint: disable=broad-except
                    self.refresh()
                    if error_callback:
                        error_callback()
                    if retry_argument:
                        kwargs[retry_argument] = True
                    return func(*args, **kwargs)
            return wrapped
        return true_decorator 
Example 16
Project: PickTrue   Author: winkidney   File: utils.py    License: MIT License 6 votes vote down vote up
def retry(max_retries=3):

    def wrapper(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            retries = 0
            while retries <= max_retries:
                retries += 1
                try:
                    return func(*args, **kwargs)
                except Exception:
                    if retries > max_retries:
                        download_logger.exception("Error occurs while execute function\n")
                        break
                    time.sleep(1)
            return None
        return wrapped

    return wrapper 
Example 17
Project: iqfeed   Author: tibkiss   File: tools.py    License: Apache License 2.0 6 votes vote down vote up
def retry(tries, exceptions=None, delay=0):
    """
    Decorator for retrying a function if exception occurs
    Source: https://gist.github.com/treo/728327

    tries -- num tries
    exceptions -- exceptions to catch
    delay -- wait between retries
    """
    exceptions_ = exceptions or (Exception, )

    def _retry(fn):
        @wraps(fn)
        def __retry(*args, **kwargs):
            for _ in range(tries+1):
                try:
                    return fn(*args, **kwargs)
                except exceptions_ as e:
                    log.warning("Exception, retrying...", exc_info=e)
                    time.sleep(delay)
            raise # If no success after tries raise last exception
        return __retry

    return _retry 
Example 18
Project: Paradrop   Author: ParadropLabs   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
def requires_auth(func):
    """
    Use as a decorator for API functions to require authorization.

    This checks the Authorization HTTP header.  It handles username and
    password as well as bearer tokens.
    """
    @functools.wraps(func)
    def decorated(self, request, *args, **kwargs):
        if not check_auth(request, self.password_manager, self.token_manager):
            out.info('HTTP {} {} {} {}'.format(request.getClientIP(),
                request.method, request.path, 401))
            request.setResponseCode(401)
            request.setHeader("WWW-Authenticate", "Basic realm=\"Login Required\"")
            return
        return func(self, request, *args, **kwargs)
    return decorated 
Example 19
Project: fine-lm   Author: akzaidi   File: expert_utils.py    License: MIT License 6 votes vote down vote up
def add_scope(scope=None, scope_fn=None):
  """Return a decorator which add a TF name/variable scope to a function.

  Note that the function returned by the decorator accept an additional 'name'
  parameter, which can overwrite the name scope given when the function is
  created.

  Args:
    scope (str): name of the scope. If None, the function name is used.
    scope_fn (fct): Either tf.name_scope or tf.variable_scope

  Returns:
    fct: the add_scope decorator
  """
  def decorator(f):

    @functools.wraps(f)
    def decorated(*args, **kwargs):
      name = kwargs.pop("name", None)  # Python 2 hack for keyword only args
      with scope_fn(name or scope or f.__name__):
        return f(*args, **kwargs)

    return decorated

  return decorator 
Example 20
Project: fine-lm   Author: akzaidi   File: common_layers.py    License: MIT License 6 votes vote down vote up
def recompute_grad(fn):
  """Decorator that recomputes the function on the backwards pass.

  Args:
    fn: a function that takes Tensors (all as positional arguments) and returns
      a tuple of Tensors.

  Returns:
    A wrapped fn that is identical to fn when called, but its activations will
    be discarded and recomputed on the backwards pass (i.e. on a call to
    tf.gradients).
  """

  @functools.wraps(fn)
  def wrapped(*args):
    return _recompute_grad(fn, args)

  return wrapped 
Example 21
Project: lirpg   Author: Hwhitetooth   File: util.py    License: MIT License 6 votes vote down vote up
def store_args(method):
    """Stores provided method args as instance attributes.
    """
    argspec = inspect.getfullargspec(method)
    defaults = {}
    if argspec.defaults is not None:
        defaults = dict(
            zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
    if argspec.kwonlydefaults is not None:
        defaults.update(argspec.kwonlydefaults)
    arg_names = argspec.args[1:]

    @functools.wraps(method)
    def wrapper(*positional_args, **keyword_args):
        self = positional_args[0]
        # Get default arg values
        args = defaults.copy()
        # Add provided arg values
        for name, value in zip(arg_names, positional_args[1:]):
            args[name] = value
        args.update(keyword_args)
        self.__dict__.update(args)
        return method(*positional_args, **keyword_args)

    return wrapper 
Example 22
Project: quart   Author: pgjones   File: utils.py    License: MIT License 6 votes vote down vote up
def run_sync(func: Callable[..., Any]) -> Callable[..., Coroutine[Any, None, None]]:
    """Ensure that the sync function is run within the event loop.

    If the *func* is not a coroutine it will be wrapped such that
    it runs in the default executor (use loop.set_default_executor
    to change). This ensures that synchronous functions do not
    block the event loop.
    """

    @wraps(func)
    async def _wrapper(*args: Any, **kwargs: Any) -> Any:
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(
            None, copy_context().run, partial(func, *args, **kwargs)
        )
        if isgenerator(result):
            return run_sync_iterable(result)  # type: ignore
        else:
            return result

    _wrapper._quart_async_wrapper = True  # type: ignore
    return _wrapper 
Example 23
Project: jupyterlab_code_formatter   Author: ryantam626   File: formatters.py    License: MIT License 6 votes vote down vote up
def handle_line_ending_and_magic(func):
    @wraps(func)
    def wrapped(self, code: str, notebook: bool, **options) -> str:
        has_semicolon = code.strip().endswith(";")

        code = re.sub(MAGIC_COMMAND_RE, "# %#", code)
        code = func(self, code, notebook, **options)
        code = re.sub(COMMENTED_MAGIC_COMMAND_RE, "%", code)

        if notebook:
            code = code.rstrip()

        if has_semicolon and notebook:
            code += ";"
        return code

    return wrapped 
Example 24
Project: xalpha   Author: refraction-ray   File: toolbox.py    License: MIT License 6 votes vote down vote up
def error_catcher(f):
    """
    装饰器,透明捕获 DateMismatch

    :param f:
    :return:
    """

    @wraps(f)
    def wrapper(*args, **kws):
        try:
            return f(*args, **kws)
        except DateMismatch as e:
            code = args[0]
            error_msg = e.reason
            error_msg += ", therefore %s cannot predict correctly" % code
            raise NonAccurate(code=code, reason=error_msg)

    return wrapper 
Example 25
Project: xalpha   Author: refraction-ray   File: provider.py    License: MIT License 6 votes vote down vote up
def data_source(s):
    """
    用以强制要求某些数据源已注册的装饰器。

    :param s: 数据源,现在仅支持 "jq"
    :return:
    """

    def protected(f):
        @wraps(f)
        def wrapper(*args, **kws):
            if getattr(thismodule, s + "_auth", False):
                return f(*args, **kws)
            else:
                raise DataSourceNotFound("Data source %s is not authenticated" % s)

        return wrapper

    return protected 
Example 26
Project: audio   Author: pytorch   File: module_utils.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def requires_module(*modules: str):
    """Decorate function to give error message if invoked without required optional modules.

    This decorator is to give better error message to users rather
    than raising ``NameError:  name 'module' is not defined`` at random places.
    """
    missing = [m for m in modules if not is_module_available(m)]

    if not missing:
        # fall through. If all the modules are available, no need to decorate
        def decorator(func):
            return func
    else:
        req = f'module: {missing[0]}' if len(missing) == 1 else f'modules: {missing}'

        def decorator(func):
            @wraps(func)
            def wrapped(*args, **kwargs):
                raise RuntimeError(f'{func.__module__}.{func.__name__} requires {req}')
            return wrapped
    return decorator 
Example 27
Project: audio   Author: pytorch   File: module_utils.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def deprecated(direction: str, version: Optional[str] = None):
    """Decorator to add deprecation message

    Args:
        direction: Migration steps to be given to users.
    """
    def decorator(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            message = (
                f'{func.__module__}.{func.__name__} has been deprecated '
                f'and will be removed from {"future" if version is None else version} release.'
                f'{direction}')
            warnings.warn(message, stacklevel=2)
            return func(*args, **kwargs)
        return wrapped
    return decorator 
Example 28
Project: indras_net   Author: gcallah   File: space.py    License: GNU General Public License v3.0 5 votes vote down vote up
def use_saved_hood(hood_func):
    @wraps(hood_func)
    def wrapper(*args, **kwargs):
        agent = args[1]
        if (agent.get("save_neighbors", False) and agent.neighbors is not
                None):
            return agent.neighbors
        return hood_func(*args, **kwargs)

    return wrapper 
Example 29
Project: indras_net   Author: gcallah   File: agent.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_null_pos(fn):
        """
        Should be used to decorate any function that uses pos[X] or pos[Y]
        """
        @wraps(fn)
        def wrapper(*args, **kwargs):
            # args[0] is self!
            if args[0].pos is None:
                user_log_err("Using the pos of an unlocated agent: "
                             + args[0].name + " in function "
                             + fn.__name__)
                return 0
            return fn(*args, **kwargs)
        return wrapper 
Example 30
Project: indras_net   Author: gcallah   File: display_methods.py    License: GNU General Public License v3.0 5 votes vote down vote up
def expects_plt(fn):
    """
    Should be used to decorate any function that uses matplotlib's pyplot.
    """
    @wraps(fn)
    def wrapper(*args, **kwargs):
        if not plt_present:
            print("Matplotlib not detected.")
            return
        return fn(*args, **kwargs)
    return wrapper