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


Python wrapt.decorator方法代码示例

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


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

示例1: versionadded

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def versionadded(reason="", version=""):
    """
    This decorator can be used to insert a "versionadded" directive
    in your function/class docstring in order to documents the
    version of the project which adds this new functionality in your library.

    :param str reason:
        Reason message which documents the addition in your library (can be omitted).

    :param str version:
        Version of your project which adds this feature.
        If you follow the `Semantic Versioning <https://semver.org/>`_,
        the version number has the format "MAJOR.MINOR.PATCH", and,
        in the case of a new functionality, the "PATCH" component should be "0".

    :return: the decorated function.
    """
    adapter = SphinxAdapter('versionadded', reason=reason, version=version)

    # noinspection PyUnusedLocal
    @wrapt.decorator(adapter=adapter)
    def wrapper(wrapped, instance, args, kwargs):
        return wrapped(*args, **kwargs)

    return wrapper 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:27,代码来源:sphinx.py

示例2: versionchanged

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def versionchanged(reason="", version=""):
    """
    This decorator can be used to insert a "versionchanged" directive
    in your function/class docstring in order to documents the
    version of the project which modifies this functionality in your library.

    :param str reason:
        Reason message which documents the modification in your library (can be omitted).

    :param str version:
        Version of your project which modifies this feature.
        If you follow the `Semantic Versioning <https://semver.org/>`_,
        the version number has the format "MAJOR.MINOR.PATCH".

    :return: the decorated function.
    """
    adapter = SphinxAdapter('versionchanged', reason=reason, version=version)

    # noinspection PyUnusedLocal
    @wrapt.decorator(adapter=adapter)
    def wrapper(wrapped, instance, args, kwargs):
        return wrapped(*args, **kwargs)

    return wrapper 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:26,代码来源:sphinx.py

示例3: _instance_method_wrapper

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def _instance_method_wrapper(wrapped, rep_invariants=None):
    if rep_invariants is None:
        return check_contracts

    @wrapt.decorator
    def wrapper(wrapped, instance, args, kwargs):
        init = getattr(instance, '__init__')
        try:
            r = _check_function_contracts(wrapped, instance, args, kwargs)
            _check_invariants(instance, rep_invariants, init.__globals__)
            _check_class_type_annotations(instance)
        except AssertionError as e:
            raise AssertionError(str(e)) from None
        else:
            return r

    return wrapper(wrapped) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:19,代码来源:__init__.py

示例4: removed_kwarg

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def removed_kwarg(old_name, message=None,
                  version=None, removal_version=None, stacklevel=3,
                  category=None):
    """Decorates a kwarg accepting function to deprecate a removed kwarg."""

    prefix = "Using the '%s' argument is deprecated" % old_name
    out_message = _utils.generate_message(
        prefix, postfix=None, message=message, version=version,
        removal_version=removal_version)

    @wrapt.decorator
    def wrapper(f, instance, args, kwargs):
        if old_name in kwargs:
            _utils.deprecation(out_message,
                               stacklevel=stacklevel, category=category)
        return f(*args, **kwargs)

    return wrapper 
开发者ID:openstack,项目名称:debtcollector,代码行数:20,代码来源:removals.py

示例5: renamed_kwarg

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def renamed_kwarg(old_name, new_name, message=None,
                  version=None, removal_version=None, stacklevel=3,
                  category=None, replace=False):
    """Decorates a kwarg accepting function to deprecate a renamed kwarg."""

    prefix = _KWARG_RENAMED_PREFIX_TPL % old_name
    postfix = _KWARG_RENAMED_POSTFIX_TPL % new_name
    out_message = _utils.generate_message(
        prefix, postfix=postfix, message=message, version=version,
        removal_version=removal_version)

    @wrapt.decorator
    def decorator(wrapped, instance, args, kwargs):
        if old_name in kwargs:
            _utils.deprecation(out_message,
                               stacklevel=stacklevel, category=category)
            if replace:
                kwargs.setdefault(new_name, kwargs.pop(old_name))
        return wrapped(*args, **kwargs)

    return decorator 
开发者ID:openstack,项目名称:debtcollector,代码行数:23,代码来源:renames.py

示例6: install_background_instrumentation

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def install_background_instrumentation():
    global background_instrumentation_installed
    if background_instrumentation_installed:
        return
    background_instrumentation_installed = True

    @wrapt.decorator
    async def wrapped_background_call(wrapped, instance, args, kwargs):
        tracked_request = TrackedRequest.instance()
        tracked_request.is_real_request = True
        tracked_request.start_span(
            operation="Job/{}.{}".format(
                instance.func.__module__, instance.func.__qualname__
            )
        )
        try:
            return await wrapped(*args, **kwargs)
        finally:
            tracked_request.stop_span()

    BackgroundTask.__call__ = wrapped_background_call(BackgroundTask.__call__) 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:23,代码来源:starlette.py

示例7: tracked_requests

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def tracked_requests():
    """
    Gather all TrackedRequests that are buffered during a test into a list.
    """
    requests = []

    @wrapt.decorator
    def capture_requests(wrapped, instance, args, kwargs):
        if instance.is_real_request and not instance.is_ignored():
            requests.append(instance)
        return wrapped(*args, **kwargs)

    orig = TrackedRequest.finish
    TrackedRequest.finish = capture_requests(orig)
    try:
        yield requests
    finally:
        TrackedRequest.finish = orig 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:20,代码来源:conftest.py

示例8: on

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def on(f):
    """Decorator for action handlers.

    The action name is inferred from the function name.

    This also decorates the method with `tornado.gen.coroutine` so that
    `~tornado.concurrent.Future` can be yielded.
    """
    action = f.__name__
    f.action = action

    @wrapt.decorator
    @tornado.gen.coroutine
    def _execute(wrapped, instance, args, kwargs):
        return wrapped(*args, **kwargs)

    return _execute(f) 
开发者ID:svenkreiss,项目名称:databench,代码行数:19,代码来源:analysis.py

示例9: reconfirm_auth

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def reconfirm_auth(func, *args, **kwargs):
    '''
    A decorator to require the user to reconfirm their login.  Useful for sensitive pages.
    '''
    from allura.lib.plugin import AuthenticationProvider

    if request.POST.get('password'):
        if AuthenticationProvider.get(request).validate_password(c.user, request.POST['password']):
            session['auth-reconfirmed'] = datetime.utcnow()
            session.save()
            kwargs.pop('password', None)
        else:
            c.form_errors['password'] = 'Invalid password.'

    allowed_timedelta = timedelta(seconds=asint(config.get('auth.reconfirm.seconds', 60)))
    last_reconfirm = session.get('auth-reconfirmed', datetime.min)
    if datetime.utcnow() - last_reconfirm <= allowed_timedelta:
        return func(*args, **kwargs)
    else:
        return render({}, 'jinja', "allura:templates/reconfirm_auth.html") 
开发者ID:apache,项目名称:allura,代码行数:22,代码来源:decorators.py

示例10: trace_xray_subsegment

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def trace_xray_subsegment(skip_args=False):
    """Can be applied to any function or method to be traced by X-Ray.

    If `skip_args` is True, the arguments of the function won't be sent to
    X-Ray.
    """

    @wrapt.decorator
    def wrapper(wrapped, instance, args, kwargs):
        metadata_extractor = (
            noop_function_metadata if skip_args else extract_function_metadata
        )
        return generic_xray_wrapper(
            wrapped,
            instance,
            args,
            kwargs,
            name=get_function_name,
            namespace="local",
            metadata_extractor=metadata_extractor,
        )

    return wrapper 
开发者ID:rackerlabs,项目名称:fleece,代码行数:25,代码来源:xray.py

示例11: require

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def require(*permissions):
        """
        Wrap a view function, verifying that the user hsa all of the specified
        permissions.
        """
        assert permissions, "Must specify at least one permission"
        for perm in permissions:
            if not perm.exists():
                raise RuntimeError(
                    "Cannot require undocumented permission %s" % (perm,))

        @wrapt.decorator
        def req(wrapped, instance, args, kwargs):
            if not can(*permissions):
                # redirect browsers when the user is not logged in, but
                # just return 403 to REST clients
                if util.is_browser() and current_user.is_anonymous:
                    return current_app.login_manager.unauthorized()
                else:
                    abort(403)
            return wrapped(*args, **kwargs)
        return req 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:24,代码来源:permissions.py

示例12: verify_status

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def verify_status(valid_status_list, raise_=False):
    """
    Decorator to help with debugging of state transitions
    If a decorated is called when the actors status is not in valid_status_list
    it will log (or raise exception if raise_ is True) the attempt.
    """
    @wrapt.decorator
    def wrapper(wrapped, instance, args, kwargs):
        # Exclude the instance variables added by superclasses
        if not instance.fsm.disable_state_checks and instance.fsm.state() not in valid_status_list:
            msg = "Invalid status %s for operation %s" % (instance.fsm, wrapped.__name__)
            if raise_:
                raise Exception(msg)
            else:
                _log.info(msg)
        x = wrapped(*args, **kwargs)
        return x
    return wrapper 
开发者ID:EricssonResearch,项目名称:calvin-base,代码行数:20,代码来源:actor.py

示例13: deprecated

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def deprecated(*args, **kwargs):
    """
    This decorator can be used to insert a "deprecated" directive
    in your function/class docstring in order to documents the
    version of the project which deprecates this functionality in your library.

    Keyword arguments can be:

    -   "reason":
        Reason message which documents the deprecation in your library (can be omitted).

    -   "version":
        Version of your project which deprecates this feature.
        If you follow the `Semantic Versioning <https://semver.org/>`_,
        the version number has the format "MAJOR.MINOR.PATCH".

    -   "action":
        A warning filter used to activate or not the deprecation warning.
        Can be one of "error", "ignore", "always", "default", "module", or "once".
        By default the deprecation warning is always emitted (the value is "always").

    -   "category":
        The warning category to use for the deprecation warning.
        By default, the category class is :class:`~DeprecationWarning`,
        you can inherit this class to define your own deprecation warning category.

    :return: the decorated function.
    """
    directive = kwargs.pop('directive', 'deprecated')
    adapter_cls = kwargs.pop('adapter_cls', SphinxAdapter)
    return _classic_deprecated(*args,
                               directive=directive,
                               adapter_cls=adapter_cls,
                               **kwargs) 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:36,代码来源:sphinx.py

示例14: cached

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def cached(func, instance, args, kwargs):
    """Simple decorator to cache result of method calls without args."""
    cache = getattr(instance, '__cache', None)
    if cache is None:
        instance.__cache = cache = {}
    try:
        return cache[func]
    except KeyError:
        cache[func] = result = func(*args, **kwargs)
        return result 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:12,代码来源:decorators.py

示例15: __doc__

# 需要导入模块: import wrapt [as 别名]
# 或者: from wrapt import decorator [as 别名]
def __doc__(self):
        doc = getattr(self.wrapped, '__doc__', None)
        return ('<wrapped by the cachedproperty decorator>%s'
                % ('\n%s' % doc if doc else '')) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:6,代码来源:decorators.py


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