當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。