当前位置: 首页>>代码示例>>Python>>正文


Python functools.wraps方法代码示例

本文整理汇总了Python中functools.wraps方法的典型用法代码示例。如果您正苦于以下问题:Python functools.wraps方法的具体用法?Python functools.wraps怎么用?Python functools.wraps使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在functools的用法示例。


在下文中一共展示了functools.wraps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: requires_auth

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:kislyuk,项目名称:aegea,代码行数:21,代码来源:decorators.py

示例2: requires_basic_auth

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:kislyuk,项目名称:aegea,代码行数:21,代码来源:decorators.py

示例3: requires_app_credentials

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:kislyuk,项目名称:aegea,代码行数:23,代码来源:decorators.py

示例4: s3_request

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:ymcui,项目名称:cmrc2019,代码行数:19,代码来源:file_utils.py

示例5: token_required

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:22,代码来源:api_helpers.py

示例6: login_required

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:18,代码来源:api_helpers.py

示例7: oidc_logout

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:zamzterz,项目名称:Flask-pyoidc,代码行数:20,代码来源:flask_pyoidc.py

示例8: requires_token

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:rs,项目名称:eve-auth-jwt,代码行数:25,代码来源:auth.py

示例9: wrap_exception

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:mbusb,项目名称:multibootusb,代码行数:20,代码来源:discover.py

示例10: translateable_docstring

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:20,代码来源:loader.py

示例11: requires_roles

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:codeforamerica,项目名称:comport,代码行数:18,代码来源:decorators.py

示例12: extractor_auth_required

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:codeforamerica,项目名称:comport,代码行数:23,代码来源:decorators.py

示例13: add_arg_scope

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:22,代码来源:scopes.py

示例14: deprecated_test

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:20,代码来源:_compat_test.py

示例15: refresh_on_error

# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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 
开发者ID:alexcasalboni,项目名称:ssm-cache-python,代码行数:27,代码来源:cache.py


注:本文中的functools.wraps方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。