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