本文整理汇总了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
示例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
示例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)
示例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
示例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
示例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__)
示例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
示例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)
示例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")
示例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
示例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
示例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
示例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)
示例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
示例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 ''))